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

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

Also note that you can assign a by using the following: int *a = (int *) (int []) { 1, 2, 3 };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.