[英]Pointers and Dynamically Allocating Arrays error in C++
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.第 4 行和第 7 行将 memory 位置分别打印为 0xd91730 和 0xd91734,我明白这一点。 However, why is the last line `( p[0] ) printing 7 on the screen.但是,为什么最后一行 `( p[0] ) 在屏幕上打印 7 。 Isn't p[0] = 3 instead, as assigned in line 5. I am not understanding this concept.不是 p[0] = 3 而是在第 5 行中指定的。我不理解这个概念。 Can anyone please help?有人可以帮忙吗? Thank you.谢谢你。
It actually does:它实际上是:
p = new int[5]
which is fine. p = new int[5]
这很好。 You allocated 5 integers worth of memory.你分配了 5 个整数值 memory。 At p[0]
you have stored the value 3 ( *p = 3
)..在p[0]
你已经存储了值 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]
).然后您将指针p
偏移 1 ( p = p + 1
).. 现在您写*p = 7
.. 当然打印P[0]
将打印 7 因为您已将 p 从其原始 position 偏移您执行了p = p + 1
(P 不再指向您执行new int[5]
时拥有的相同 memory 地址)。
You never decreased the pointer back to point to 3.您从未将指针减小回指向 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.如果你在增加它之后delete[] p
,它会是未定义的行为,并且可能会崩溃,因为你正在删除 memory 位置,因为你增加了 P。
If you wanted it to print 3, you'd have to do P = P - 1
after writing 7 to P[1].如果您希望它打印 3,则必须在将 7 写入 P[1] 之后执行P = P - 1
。
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.因此,您正在取消引用 memory 位置 x 指向指针前面的位置。
In your code.在你的代码中。 After you have allocated memory you move the pointer:分配 memory 后,移动指针:
p = p+1; // This moves p to point at the next location in memory.
Now your memory looks like this:现在您的 memory 看起来像这样:
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
.取消引用 p 将为您提供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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.