通过引用传递数组

是否允许通过引用传递数组?

 void foo(double& *bar)

看来我的编译器说不行。为什么?通过引用传递数组的正确方法是什么?或者在附近工作?我有一个数组参数,我的方法应该修改它,然后我应该检索它。或者,我可以使这个数组成为类成员,这样可以很好地工作,但是它对于我的代码的其他部分有很多缺点(我希望避免这些缺点)。

谢谢,还有问候。

198619 次浏览

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.

Like the other answer says, put the & after the *.

This brings up an interesting point that can be confusing sometimes: types should be read from right to left. For example, this is (starting from the rightmost *) a pointer to a constant pointer to an int.

int * const *x;

What you wrote would therefore be a pointer to a reference, which is not possible.

As you are using C++, the obligatory suggestion that's still missing here, is to use std::vector<double>.

You can easily pass it by reference:

void foo(std::vector<double>& bar) {}

And if you have C++11 support, also have a look at std::array.

For reference:

Yes, but when argument matching for a reference, the implicit array to pointer 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 [] are distinct 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 42 elements, 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, since there's no way to recover it once you're inside the function.

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.

8.3.5.8 If the type of a parameter includes a type of the form “pointer to array of unknown bound of T” or “reference to array of unknown bound of T,” the program is ill-formed

Here, Erik explains every way pass an array by reference: https://stackoverflow.com/a/5724184/5090928.

Similarly, you can create an array reference variable like so:

int arr1[] = {1, 2, 3, 4, 5};
int(&arr2)[5] = arr1;