简体   繁体   中英

Pointer to array as function parameter

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...

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM