CodeKingPlusPlus
CodeKingPlusPlus

Reputation: 16081

Passing an array as a pointer

I have a function that takes an array of fixed size. The contents of the array will be modified in this function so I want to pass the array as a pointer.

Here are the definitions of my arrays:

int u[] = {1, 0 , a};   //a is an integer
int v[] = {1, 0 , a};   //a is an integer

Here is my prototype:

void New_Values(int* u[3], int* v[3], const int q);

Here is my function call:

New_Values(&u, &v, q);   //q is an integer

I get the compiler errors:

passing argument 1 of ‘New_Values’ from incompatible pointer type

and

passing argument 2 of ‘New_Values’ from incompatible pointer type

Upvotes: 0

Views: 174

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753970

Only exceptionally will you want to pass a pointer to an array to a function; you'll most likely do as the others have suggested:

void New_Values(int u[], int v[], int q);
void New_Values(int *u,  int *v,  int q);

(These declarations are equivalent; the compiler treats the former as if it was written like the latter, so most often you'll see simple pointer notation rather than array notation.)

And the call:

New_Values(u, v, q);

If you really want to play with pointers to arrays, you have to use the correct notation — what you tried to specify was an array of integer pointers, not a pointer to an array of integers.

void New_Values(int (*v)[], int (*v)[], int q);

And the call:

New_Values(&u, &v, q);

Inside New_Values(), you'd use:

(*v)[i] = (*u)[j] + q;

This is an illustration of C's 'declaration syntax matches syntax when used'.

Note that I dropped the const from the int parameter. It isn't completely pointless, but there's no danger of the called function modifying a value in the calling function if it does modify the parameter.

Upvotes: 4

P.P
P.P

Reputation: 121397

Just pass the array names as arrays decay into pointers.

Pass as:

New_Values(u, v, q);

and function prototype:

void New_Values(int* u, int* v, const int q);

Upvotes: 1

cnicutar
cnicutar

Reputation: 182649

Just make the function take pointers:

void New_Values(int *u, int *v, const int q);

And just use them like arrays. In this context the array decays into a pointer to the first element. Also, you should drop the & from the function call and just say: New_Values(u, v, q);

Upvotes: 3

Related Questions