Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Array in C? [duplicate]

Tags:

arrays

c

pointers

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; 
}
like image 795
SplineO Avatar asked Jun 11 '15 12:06

SplineO


2 Answers

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

like image 131
unwind Avatar answered Oct 14 '22 18:10

unwind


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.

like image 1
P.P Avatar answered Oct 14 '22 18:10

P.P