如何在C++中将指向int数组的指针设置为NULL?

the*_*est -2 c++ arrays pointers memory-leaks memory-management

对于指向int的指针,我可以这样做 -

int *p = new int;
*p = 10;

delete p; // Step 1: Memory Freed
p = 0; // Step 2: Pointer set to NULL
Run Code Online (Sandbox Code Playgroud)

现在,如果我有一个指向int数组的指针 -

int *p = new int[10];
p[1] = 1;
p[5] = 5;
delete[] p; // Step 1: Memory freed corresponding to whole array
Run Code Online (Sandbox Code Playgroud)

现在,如何在这种情况下实现"第2步"?

Jos*_*eld 6

你没有一个int指针数组.你只有一个数组int.由于你只有一个指针,p你可以像以前一样做同样的事情:

p = 0; // or nullptr, preferably
Run Code Online (Sandbox Code Playgroud)

如果你确实有一个数组int的指针,你可能会在一个循环中分配它们.以同样的方式,您可以释放它们并将它们设置0为循环:

int* array[10];
for (auto& p : array) {
  p = new int;
}

// Some time later...

for (auto& p : array) {
  delete p;
  p = 0;
}
Run Code Online (Sandbox Code Playgroud)

一定要考虑是否需要后您的指针设置为null delete荷兰国际集团他们.