小编bob*_*bob的帖子

删除动态分配的变量设置指针为0

我无法理解这段代码的结尾(array = 0;):

#include <iostream>

int main()
{
    std::cout << "Enter a positive integer: ";
    int length;
    std::cin >> length;

    int *array = new int[length];

    std::cout << "I just allocated an array of integers of length " << length << '\n';

    array[0] = 5; // set element 0 to value 5

    delete[] array; // use array delete to deallocate array
    array = 0; // use nullptr instead of 0 in C++11

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

最后,删除动态分配的数组(返回到OS),然后分配值0.

为什么这样做?数组返回操作系统后,无需为其赋值0,对吗?

代码来自:http …

c++ arrays pointers memory-management dynamic-allocation

7
推荐指数
2
解决办法
1275
查看次数