6

Pointers are a difficult topic for sure, but I have come across this snippet and I just can't figure out what the p[-1] is:

#include <stdio.h> 
int main(void) { 
    int t[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, *p = t; 

    p += 2; 
    p += p[-1]; 
    printf("%d",*p); 
    return 0; 
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
SplineO
  • 63
  • 2
  • First, you add 2 to the pointer p, so it will point to 2 addresses further than before (so it now points to the address of `t[2]`). Now you access one address before the one it is pointing to, resulting in it pointing to the address containing the `2` (or `t[1]`). – moffeltje Jun 11 '15 at 12:23

2 Answers2

9

Any time you see an expression like a[b] in C, you can mentally think that *(a + b) is happening.

So, it's just "the contents of the element before the one p is pointing at right now".

Since p is at t + 2, p[-1] refers to t[2 + (-1)] i.e. t[1].

unwind
  • 391,730
  • 64
  • 469
  • 606
1
p += p[-1]; 

can be written as

p = p + *(p-1);

At that point, p points to the 3rd element of the array (value 3) and *(p-1) is 2.

So, it's equivalent to

p = p+2;

and printing *p would print 5.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Awesome guys, thanks! That was quick! Now I feel a bit dumb! But thanks a million for the thorough explanations! – SplineO Jun 11 '15 at 12:32