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; 
}
1
  • 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]). Commented Jun 11, 2015 at 12:23

2 Answers 2

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].

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Awesome guys, thanks! That was quick! Now I feel a bit dumb! But thanks a million for the thorough explanations!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.