Pointer

Why p[-1] = 4?
*p++ = 1 not 2?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main() {
int a [ 10 ] = { 4, 1, 2};
int* p = &a[ 0 ];//*p=4
p++;//*p=1
cout << p[-1] << '\n';
cout << *p++ << '\n';

}
p++ works differently than you think. Line 9 will run like this :
1
2
cout << *p << '\n';
/* then */p++;

If you would like the other way around, use ++p.
Thanks, Why p[-1] = 4?
I do not know for sure, but I will take a stab at it.

Line 6, you set p[0] = a[0].
Line 7, you increment p, which means that now p[0] = a[1], the next point in the memory.
So on line 8, when you do p[-1], it looks at the memory before the current p[0], which happens to be a[0] = 4.

I hope someone can either verify or correct this.
Topic archived. No new replies allowed.