C++ pass an array by reference C++ pass an array by reference arrays arrays

C++ pass an array by reference


Arrays can only be passed by reference, actually:

void foo(double (&bar)[10]){}

This prevents you from doing things like:

double arr[20];foo(arr); // won't compile

To be able to pass an arbitrary size array to foo, make it a template and capture the size of the array at compile time:

template<typename T, size_t N>void foo(T (&bar)[N]){    // use N here}

You should seriously consider using std::vector, or if you have a compiler that supports c++11, std::array.


Yes, but when argument matching for a reference, the implicit array topointer isn't automatic, so you need something like:

void foo( double (&array)[42] );

or

void foo( double (&array)[] );

Be aware, however, that when matching, double [42] and double [] aredistinct types. If you have an array of an unknown dimension, it will match the second, but not the first, and if you have an array with 42elements, it will match the first but not the second. (The latter is,IMHO, very counter-intuitive.)

In the second case, you'll also have to pass the dimension, sincethere's no way to recover it once you're inside the function.


If you want to modify just the elements:

void foo(double *bar);

is enough.

If you want to modify the address to (e.g.: realloc), but it doesn't work for arrays:

void foo(double *&bar);

is the correct form.