int *ptr = (int*)(&a + 1);

int *ptr = (int*)(&a + 1);  // what happen here ?

The address of the array is taken, and then 1 is added to it, which produces a pointer pointing sizeof a bytes past the beginning of a. That pointer is then cast to an int*, and that is assigned to ptr. The same could be achieved with

int *ptr = &a[5];

in this case.

Then ptr - 1 is a pointer pointing sizeof(int) bytes before ptr, that is, to &a[4], and *(ptr - 1) is a[4].

Pointer arithmetic is done in units of "size of pointee". Since &a is a pointer to an array of 5 int - an int (*)[5], adding 1 to it moves it 5*sizeof(int) bytes.


&a is a pointer to pointer to int[5] and thus &a + 1 is again a pointer to int[5]. Loose the & and all should be fine(and also you will no longer need the cast):

int *ptr = a + 1;

Tags:

C

Pointers