如何在 C++ 中将指向 int 数组的指针设置为 NULL
How to set pointer to an int array to NULL in C++?
对于指向整数的指针,我可以做 -
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。
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”