Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to array as function parameter

Tags:

c

pointers

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

like image 251
MPelletier Avatar asked Mar 16 '12 20:03

MPelletier


People also ask

How do you pass a pointer to an array to a function?

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

Can we pass an array in function as a parameter?

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.

Can you assign a pointer to an array?

You cannot assign a new pointer value to an array name. The array name will always point to the first element of the array.


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

like image 199
cnicutar Avatar answered Sep 16 '22 23:09

cnicutar


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.

like image 25
Knight71 Avatar answered Sep 17 '22 23:09

Knight71