I wrote a function which takes a pointer to an array to initialize its values:
#define FIXED_SIZE 256
int Foo(int *pArray[FIXED_SIZE])
{
/*...*/
}
//Call:
int array[FIXED_SIZE];
Foo(&array);
And it doesn't compile:
error C2664: 'Foo' : cannot convert parameter 1 from 'int (*__w64 )[256]' to 'int *[]'
However, I hacked this together:
typedef int FixedArray[FIXED_SIZE];
int Foo(FixedArray *pArray)
{
/*...*/
}
//Call:
FixedArray array;
Foo(&array);
And it works. What am I missing in the first definition? I thought the two would be equivalent...
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().
Just like normal variables, Arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.
You cannot assign a new pointer value to an array name. The array name will always point to the first element of the array.
int Foo(int *pArray[FIXED_SIZE])
{
/*...*/
}
In the first case, pArray
is an array of pointers, not a pointer to an array.
You need parentheses to use a pointer to an array:
int Foo(int (*pArray)[FIXED_SIZE])
You get this for free with the typedef
(since it's already a type, the *
has a different meaning). Put differently, the typedef
sort of comes with its own parentheses.
Note: experience shows that in 99% of the cases where someone uses a pointer to an array, they could and should actually just use a pointer to the first element.
One simple thing is to remember the clockwise-spiral rule which can be found at http://c-faq.com/decl/spiral.anderson.html
That would evaluate the first one to be an array of pointers . The second is pointer to array of fixed size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With