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?