我两周前开始自学 C++,现在我正在学习指针。为什么下面的代码不能按我预期的方式工作,删除后我在数组中看到相同的值。我以为数组会被删除,指针会指向堆中的某个随机整数,除非我写 dArray = NULL。有人可以详细说明一下吗?我不知道我做错了什么。谢谢。
PS:我在 Mac 上使用 Xcode。
代码:
#include <iostream>
using namespace std;
int main() {
int *dArray = new int[5];
for(int i=0; i<5; i++) {
dArray[i] = i*2;
}
cout << "Show array:" << endl;
for(int i=0; i<5; i++) {
cout << dArray[i] << endl;
}
delete [] dArray;
// show array after deletion
cout << "After deletion:" << endl;
for(int i=0; i<5; i++) {
cout << dArray[i] << endl;
}
return 0;
}
输出:
Show array:
0
2
4
6
8
After deletion:
0
2
4
6
8
Program ended with exit code: 0
最佳答案
delete
不会更改指针的值。这只是意味着指针指向的内容不再合法访问(给出未定义的行为)。
在很多情况下(比如你的)程序可能看起来可以工作,但是改变一些东西(比如添加另一个 new
)并且它会以奇怪且难以追踪的方式失败......删除后将指针置0,至少可以让故障更容易识别。
关于c++ - 指针 - 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30342365/