Pointer to an array as a function parameter

I wrote a function that 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 does not compile:

error C2664: 'Foo': cannot convert parameter 1 from 'int (* __ w64) [256]' to 'int * []'

However, I hacked it 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 they would be equivalent ...

+6
source share
3 answers
 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 will get this for free with typedef (since it is already a type, * has a different meaning). In other words, typedef has its own parentheses.

Note: experience shows that in 99% of cases when someone uses a pointer to an array, they can and should simply use a pointer to the first element .

+13
source

One simple thing is to remember the clockwise rule, which can be found at http://c-faq.com/decl/spiral.anderson.html

This would evaluate first to be an array of pointers. The second is a pointer to a fixed-size array.

+2
source

The array decays to a pointer. Thus, it works in the second case. In the first case, the function parameter is an array of pointers, but not a pointer to an integer pointing to the first element in the sequence.

0
source

Source: https://habr.com/ru/post/910948/


All Articles