Home >Backend Development >C++ >How Can Arrays Be Passed by Reference in C ?
Passing Arrays by Reference in C
Question:
Can arrays be passed by reference in C ? If so, what is the proper syntax?
Answer:
Yes, arrays can only be passed by reference in C . The proper syntax is:
void foo(double (&bar)[10])
where bar is the array reference and 10 is the size of the array.
However, this syntax prevents passing arrays of arbitrary sizes. To pass an array of any size, a templated function can be used:
template<typename T, size_t N> void foo(T (&bar)[N])
where N captures the array size at compile time.
Alternatives:
Consider using std::vector or std::array (in C 11) as alternatives to passing arrays by reference. These offer a more flexible and safe way to handle collections of data.
The above is the detailed content of How Can Arrays Be Passed by Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!