KartalKaan's blog

By KartalKaan, 12 years ago, In English

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.

  • Vote: I like it
  • +9
  • Vote: I do not like it

»
12 years ago, hide # |
 
Vote: I like it +10 Vote: I do not like it

The first code has an ampersand before p, not before p+1. It's high-priority unary operator, and &p+1 is equal to (&p)+1.

Basically, p+x (where p is a T* and x is an int) 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.