Hello everyone! I have two codes, they print different things but I don't know why. The first one is :
#include <stdio.h>
int main()
{
int p[6]={1,2,3,4,5,6};
int *q=(int *)(&p+1);
printf("%ld\n",q-p);
return 0;
}
And the second one :
#include <stdio.h>
int main()
{
int p[6]={1,2,3,4,5,6};
int *q=(int *)(p+1);
printf("%ld\n",q-p);
return 0;
}
First code prints 6, whereas the second one prints 1. The only difference is that the first code has an ampersand before "p+1". Do you know the reason? Thanks.
The first code has an ampersand before
p
, not beforep+1
. It's high-priority unary operator, and&p+1
is equal to(&p)+1
.Basically,
p+x
(wherep
is aT*
andx
is anint
) is equivalent to(T*)((char*)p + sizeof(*p)*x)
, i.e. if you add one to a pointer, it shifts by one element to high addresses.When you take address of
p
, you get a pointer to an array of six integers. Size of such array is six integers, and when you add one to this pointer, you get a pointer to the byte past end of the array (six integers after the beginning).But, if you use
p
as a pointer itself, it behaves like pointer to integers, and adding one to it results into pointer to the second element of an array.Thanks for explanation. We have an important exam tomorrow which is mostly about pointers and maths. Waiting for your good wishes :)