2

Let us consider the below code:

int y = 20;
int *pointer_of_y = y; //Intentionally missed &
printf("%p\n",pointer_of_y);
printf("%p\n",&y);
printf("%d\n",*pointer_of_y);

Output:

0x14 //Value of 20 in hex
0x7fff56747af8 //Address of Y Variable
Segmentation fault: 11 //Value at pointer: Due to missing &

The above code does not execute because I have missed & in pointer initialisation.

Let us consider the same code if it is initialised as array.

int x[]= {10,20,30,40};
int *pointer_of_x = x;
printf("%p\n",pointer_of_x);
printf("%p\n",&x);
printf("%d\n",*pointer_of_x);

The output :

0x7fff5b5eaad0  //Pointer value
0x7fff5b5eaad0  //Address of x
10 //Value at address pointed

How does the second example work even though I have missed the & in the pointer initialisation. Why does being a array make a difference?

2 Answers 2

4

When the name of an array is used in an expression context other than as the operand to sizeof or & it decays to a pointer to its first element.

So here -

int x[]= {10,20,30,40};

x will give address of first element of array and has type int *. Therefore this works -

int *pointer_of_x = x;   //works 
Sign up to request clarification or add additional context in comments.

5 Comments

I'd remove "the name of", as the name is not relevant in this context.
@alk I think it is relevant, but more accurate would be the identifier of
@FelixPalmen: In C names or identifiers are for the parser only. "Expression evaluating to an array" might do.
@alk so? doesn't matter at the syntax level, and that's what was asked.
@FelixPalmen: The question is not about syntax (syntax error: int i = 1; int * pi := i;). It is about semantics (semantical "error": int i = 1; int * pi = i;)
2

If an array of type T is assigned to a pointer of type T* then the array decays to the address of its 1st element.

Comments

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.