Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a pointer as array in function in C?

Tags:

arrays

c

pointers

void f(int *a, int n)
{
     int i;
     for (i = 0; i < n; i++)
     {
         printf("%d\n", *(a+i));
     }
 }

The above code worked ok if in main() I called:

int a[] = {1,2,3};
int *p = a;

f(a, 3);

But if in main(), I did:

int *a =(int*) {1,2,3};

f(a, 3);

Then, the program will crash. I know this might look weird but I am studying and want to know the differences.

like image 463
ipkiss Avatar asked Jan 16 '23 21:01

ipkiss


1 Answers

It's because of the cast. This line says:

int *a =(int*) {1,2,3};

Treat the array {1,2,3} as a pointer to an int. On a 32 bit machine, the value of the pointer is now 1, which is not what you want.

However, when you do:

int *p = a;

The compiler knows that it can decay the array name to a pointer to it's first element. It's like you'd actually written:

int *p = &(a[0]);

Similarly, you can just pass a straight in to the function, as the compiler will also decay the array name to a pointer when used as a function argument:

int a[] = {1,2,3};
int *p = &(a[0]);

f(p, 3) 
f(a, 3); // these two are equivalent
like image 96
Timothy Jones Avatar answered Jan 24 '23 17:01

Timothy Jones