Pointer array in C?

Pointers are a tough topic, but I came across this snippet, and I just can't figure out what p[-1] :

 #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; } 
+6
source share
2 answers

Whenever you see an expression like a[b] in C, you can mentally think what happens *(a + b) .

So this is just "the contents of the element before one p points right now."

Since p is in t + 2 , p[-1] refers to t[2 + (-1)] ie t[1] .

+9
source
 p += p[-1]; 

can be written as

 p = p + *(p-1); 

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

So this is equivalent

 p = p+2; 

and print *p will print 5 .

+1
source

Source: https://habr.com/ru/post/988923/


All Articles