Reputation: 16657
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...
Upvotes: 6
Views: 9327
Reputation: 2949
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.
Upvotes: 1
Reputation: 34625
An array decays to a pointer. So, it works in the second case. While in the first case, the function parameter is an array of pointers but not a pointer to integer pointing to the first element in the sequence.
Upvotes: -1
Reputation: 182619
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.
Upvotes: 15