Reputation: 83
I am getting an introduction to pointers and I don't understand the following code.
int main(){
int *p;
p=new int[5];
cout << p <<endl; // line 4
*p=3;
p=p+1;
cout <<p <<endl; // line 7
*p=7;
cout << p[0] <<endl;
}
line 4 and line 7 prints the memory location as 0xd91730 and 0xd91734 respectively and I understand that. However, why is the last line `( p[0] ) printing 7 on the screen. Isn't p[0] = 3 instead, as assigned in line 5. I am not understanding this concept. Can anyone please help? Thank you.
Upvotes: 0
Views: 60
Reputation: 264571
When dealing with pointers the square bracket notation is just way of dereferencing a pointer.
p[x] is syntactically equivalent to *(p + x)
So you are de-referencing the memory location x points ahead of the pointer.
In your code. After you have allocated memory you move the pointer:
p = p+1; // This moves p to point at the next location in memory.
Now your memory looks like this:
Memory 0xd91730 [0, 0, 0 ,3] => 4 bytes
p --------->0xd91734 [0, 0, 0, 7] => 4 bytes (yes I am making an assumption
0xd91738 [?, ?, ?, ?] about layout for demonstrating
0xd9173c [?, ?, ?, ?] purposes)
De-referencing p will give you the content at 0xs91734
.
Try adding the following line:
std::cout << p[-1] << "\n"; // Should return the 3 you were looking for
Just for fun try:
std::cout << 0[p] << "\n"; // Blows your mind but works.
// Pointer + integer is a pointer.
// integer + Pointer is also a pointer.
// So 0[p] => *(0 + p) => *(p + 0) => p[0]
Upvotes: 1
Reputation: 23485
It actually does:
p = new int[5]
which is fine. You allocated 5 integers worth of memory.
At p[0]
you have stored the value 3 (*p = 3
)..
You then offset the pointer p
by 1 (p = p + 1
).. and now you wrote *p = 7
.. Of course printing P[0]
is going to print 7 because you've offset p from its original position when you did p = p + 1
(P no longer points to the same memory address you had when you did new int[5]
).
You never decreased the pointer back to point to 3.
If you did delete[] p
after increasing it, it'd be undefined behaviour and possibly crash on you because you are deleting memory location since you increased P.
If you wanted it to print 3, you'd have to do P = P - 1
after writing 7 to P[1].
Upvotes: 2