C++ pass an array by reference

kiriloff picture kiriloff · Apr 4, 2012 · Viewed 151.8k times · Source

is this allowed to pass an array by reference ?

 void foo(double& *bar) 

Seems that my compiler says no. Why? What is the proper way to pass an array by reference? Or a work around? I have an array argument that my method should modify and that I should retrieve afterwards. Alternatively, I could make this array a class member, which works fine, but it has many drawbacks for other part of my code (that I would like to avoid).

Thanks and regards.

Answer

jrok picture jrok · Apr 4, 2012

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.