How to pass a vector to a function in C ? (By Reference)
To pass a vector by reference in C , use std::vector
& for modification or const std::vector & for read-only access—avoiding copies, enabling direct changes, and ensuring efficiency and safety.

To pass a vector to a function by reference in C , you declare the parameter as std::vector<t>&amp;</t> — not std::vector<t></t> (which copies) or std::vector<t>*</t> (which uses a pointer). This avoids copying all elements and lets the function modify the original vector directly.
Declare the parameter as a non-const lvalue reference
Use std::vector<int>&amp;</int> (or whatever type) if the function needs to change the vector — e.g., add, remove, or update elements.
- Inside the function, operations like
v.push_back(42)orv[0] = 99affect the original vector. - No extra memory is allocated for the vector data — only the reference itself (typically pointer-sized) is passed.
Prefer const reference when you only read the vector
If the function only inspects the vector (e.g., computes sum or finds max), use const std::vector<t>&amp;</t>.
- This prevents accidental modification and signals intent clearly.
- Still avoids copying — just as efficient as non-const reference.
- Allows calling the function with temporaries or const vectors.
Don’t forget to include and use std::
Make sure your code includes the header and properly scopes the type:
#include <vector></vector>- Either write
std::vector<double>&amp; v</double>, or useusing std::vector;(notusing namespace std;in headers).
Avoid common pitfalls
Two mistakes beginners often make:
- Passing by value (
std::vector<int> v</int>) — silently copies everything, which is slow for large vectors. - Using raw pointers unnecessarily —
std::vector<int>* v</int>adds indirection and null-checking overhead without benefit. - Returning a reference to a local vector — that’s undefined behavior.
Basically just match the reference type to your intent: & for modification, const&amp; for reading — and you’re good.
The above is the detailed content of How to pass a vector to a function in C ? (By Reference). For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20528
7
13637
4




