Passing an array by reference

2019-01-01 08:28发布

问题:

How does passing a statically allocated array by reference work?

void foo(int (&myArray)[100])
{
}

int main()
{
    int a[100];
    foo(a);
}

Does (&myArray)[100] have any meaning or its just a syntax to pass any array by reference? I don\'t understand separate parenthesis followed by big brackets here. Thanks.

回答1:

It\'s a syntax for array references - you need to use (&array) to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];.

EDIT: Some clarification.

void foo(int * x);
void foo(int x[100]);
void foo(int x[]);

These three are different ways of declaring the same function. They\'re all treated as taking an int * parameter, you can pass any size array to them.

void foo(int (&x)[100]);

This only accepts arrays of 100 integers. You can safely use sizeof on x

void foo(int & x[100]); // error

This is parsed as an \"array of references\" - which isn\'t legal.



回答2:

It\'s just the required syntax:

void Func(int (&myArray)[100])

^ Pass array of 100 int by reference the parameters name is myArray;

void Func(int* myArray)

^ Pass an array. Array decays to a pointer. Thus you lose size information.

void Func(int (*myFunc)(double))

^ Pass a function pointer. The function returns an int and takes a double. The parameter name is myFunc.



回答3:

It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don\'t use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

E.g. int &myArray[100] // array of references

So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

E.g int (&myArray)[100] // reference of an array of 100 ints



回答4:

Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.



标签: c++ arrays