#include<stdio.h>
int main(){
int a[5] = {0,1,2,3,4};
int * ptr;
ptr =(int *) &a;
printf("\n&a:%u,&a[0]:%u,ptr:%u\n",&a,&a[0],ptr);
ptr = (int*)(&a+1);
printf("\n&a:%u,&a[0]:%u,ptr:%u\n",&a,&a[0],ptr);
ptr = (int*)(&a);
ptr = (int*)(&a[0]+4);
printf("\n&a:%u,&a[0]:%u,ptr:%u,*ptr:%d\n",&a,&a[0],ptr,*ptr);
return 0;
}
o/p:
&a:3213284540,&a[0]:3213284540,ptr:3213284540
&a:3213284540,&a[0]:3213284540,ptr:3213284560
&a:3213284540,&a[0]:3213284540,ptr:3213284556,*ptr:4
In the above code &a and &a[0] gives the same address 3213284540. But the two cases when added with 1 gives different address.
&a[0]+1 => 3213284540 + 4 = 3213284544 [The value stored in this address is '1']
&a+1 => 3213284540 + (5*4) = 3213284560 [Goes Out of bounds of the array]
&a+1 is equivalent to sizeof(array)+1.
But how the compiler interprets this
&a[0]+1and&a+1?
It’s pointer arithmetic, so it’s always important to know the pointed types and one basic thing: adding
1to a pointer makes it point to some “next” element.In your example
&a[0]is of typeint *so adding 1 moves thepointer to the next int. So the address should increase by 4/8
bytes or so, depending on
sizeof(int)However,
&ais of typeint (*)[5]. So adding 1 to it moves thepointer to the next array. In effect, the address should increase
by
sizeof(a).Side note: use
%pwhen printing pointer values.