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

How to set pointer to an int array to NULL in C++?

本文关键字:数组 指针 设置 NULL int C++      更新时间:2023-10-16

对于指向整数的指针,我可以做 -

int *p = new int;
*p = 10;
delete p; // Step 1: Memory Freed
p = 0; // Step 2: Pointer set to NULL

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

int *p = new int[10];
p[1] = 1;
p[5] = 5;
delete[] p; // Step 1: Memory freed corresponding to whole array

现在,如何实现这种情况的"步骤2"?

您没有int指针数组。你只有一个int数组.由于您只有一个指针,p ,您可以执行与以前相同的操作:

p = 0; // or nullptr, preferably

如果您确实有一个int指针数组,则可能会在循环中分配它们。同样,您可以解除分配它们并将它们设置为循环0

int* array[10];
for (auto& p : array) {
  p = new int;
}
// Some time later...
for (auto& p : array) {
  delete p;
  p = 0;
}
请考虑是否需要在

delete指针后将指针设置为 null。