In the below two lines,
char a[5]={1,2,3,4,5};
char *ptr=(char *)(&a+1);
printf(\"%d\",*(ptr-1));
This prints 5 on screen.Whereas when use
The difference is in the type of the pointer that you get:
a
by itself represents a pointer to the initial element of the array. When interpreted in that way, e.g. in an expression a+1
, the pointer is considered to point to a single character.&a
, on the other hand, the pointer points to an array of five characters.When you add an integer to a pointer, the number of bytes the pointer is moved is determined by the type of the object pointer to by the pointer. In case the pointer points to char
, adding N
advances the pointer by N
bytes. In case the pointer points to an array of five char
s, adding N
advances the pointer by 5*N
bytes.
That's precisely the difference that you are getting: your first example advances the pointer to the element one past the end of the array (which is legal), and then move it back to the last element. Your second example, on the other hand, advances the pointer to the second element, and then moves it back to point to the initial element of the array.