Passing arrays via reference?

arrays, c++, pointers

Solution

The type `int *a[2]` means array of 2 pointers to `int`, but the expression `&a` with the definition `int a[2]` means pointer to an array of 2 `int`. Both are different types and there is no conversion among them. As Vlad already mentioned, to provide the proper type you need to add parenthesis:

void setvalues( int (*c)[2] )

Or you could use actual references in C++:

void setvalues( int (&c)[2] )

In the later case you don't need to use the address-of operator or dereference it inside the `setvalue` function:

int a[2];
setvalues(a); // this is a reference to the array

A simpler way to write the code is to use `typedef`:

typedef int twoints[2];
void setvalue( toints& c );
int main() {
   twoints a; // this is int a[2];
   setvalue(a);
}

Problem

I'm fairly new to C++ and I recently came across this problem. This code will obviously work: ``` void setvalues(int *c, int *d) { (*c) = 1; (*d) = 2; } int main() { int a, b; setvalues(&a, &b); std::cout << a << b; } ``` So why does this return an error? Visual C++ 2010 error: `C2664: 'setvalues' : cannot convert parameter 1 from 'int (*)[2]' to 'int *[]'` ``` void setvalues(int *c[2], int *d[2]) { (*c[1]) = 1; (*d[1]) = 2; } int main() { int a[2], b[2]; setvalues(&a, &b); std::cout << a[1] << b[1]; } ``` What's different about pointers to arrays? I searched around but no luck.

Original source