c++ - 指针 - 删除

标签 c++ arrays pointers

我两周前开始自学 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/

相关文章:

c - 我的程序在 C 中反转字符串有什么问题?

c++动态分配指针指向的类的拷贝

c++ - .cpp 文件中的 Objective C 语法?

c++ - 将数字转换为文本时出错

mysql - While语句不输出第一行数据中的复选框

java - 在二维数组中生成随机数

c++ - STL Pass 迭代器与容器

arrays - 无法使用 CountableRange<Int> 类型的索引为 Array<Element> 类型的值添加下标

c - 在 C 中表示元胞数组(来自 MATLAB)

c++ - 使用中间转换将 char* 缓冲区设置为 int*