#include <stdio.h>
int main(void)
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int*)(&a + 1); // what happens here ?
printf("%d %d\n", *(a + 1), *(ptr - 1));
return 0;
}
I expected the answer to be 1 but 'm getting 5 .. Why ?
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;
int *ptr = (int*)(&a + 1); // what happen here ?
a= address of first element of array: a[0] (address of int)
&a =address of array a,same value with "a", but type is address of array,so expression "(&a + 1)" is pointer to next array "a". (ptr - 1): pointer to previous int of ptr, that mean the pointer of last element of array "a".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With