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;
}
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].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With