6

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

asked Mar 16, 2012 at 20:07

3 Answers 3

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

answered Mar 16, 2012 at 20:09
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, pointer to first element as well as the size (if needed, which it probably is).
1

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.

answered Aug 7, 2013 at 12:10

Comments

-1

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.

answered Mar 16, 2012 at 20:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.