Passing arrays by reference?

I am new to C ++ and I recently ran into 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 is the difference between a pointer to arrays? I searched around but no luck.

+7
source share
3 answers

The type int *a[2] means an array of 2 pointers to int , but the expression &a with the definition int a[2] means a pointer to an array of 2 int . Both are different types and there is no conversion between them. As Vlad already said, to ensure the correct type you need to add brackets:

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

Or you can use the actual links in C ++:

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

In a later case, you do not need to use the address of the operator or setvalue it inside the setvalue function:

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

An easier way to write code is to use typedef :

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

To pass by reference, there must be void setvalues(int (&c)[2], int (&d)[2]) . And the caller must be setvalues(a, b); . Otherwise, you indicate pointers with pointers at best.

+3
source

Here's how you fix it:

 void setvalues(int c[], int d[]) { c[1] = 1; d[1] = 2; } int main() { int a[2],b[2]; setvalues(a, b); std::cout<<a[1]<<b[1]; } 

When you declare an array like this: int a[2],b[2]; , then a and b already point to the beginning of these arrays.

And when you execute a[0] , that is, when you actually parse the array with some offset to access the array element. a[1] , for example, matches *(a+1)

Link: http://www.cplusplus.com/doc/tutorial/arrays/

+2
source

All Articles