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.
It’s because of the cast. This line says:
Treat the array
{1,2,3}as a pointer to an int. On a 32 bit machine, the value of the pointer is now1, which is not what you want.However, when you do:
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:
Similarly, you can just pass
astraight in to the function, as the compiler will also decay the array name to a pointer when used as a function argument: