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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With