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.
The type
int *a[2]means array of 2 pointers toint, but the expression&awith the definitionint a[2]means pointer to an array of 2int. 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:Or you could use actual references in C++:
In the later case you don’t need to use the address-of operator or dereference it inside the
setvaluefunction:A simpler way to write the code is to use
typedef: