删除指针数组 (C++) 中的元素

deleting elements in array of pointer (C++)

本文关键字:元素 C++ 指针 数组 删除      更新时间:2023-10-16

假设我有一个指针数组,例如

Person** p = new Person*[5]
// p is filled with five person pointer (say p[2] = *John where John is an object of person
// now we want to remove p[2]
delete p[2];
p[2] = p[3];
p[3] = p[4];
p[4] = nullptr;

除非我删除删除和nullptr行,否则无法编译该程序。 为什么会这样?如果我不删除 p[2],应该有问题,因为我无法再次访问 john?

如果您有这种模式,请使用std::list(或std::vector(。标准容器将比您提出的大多数解决方案更好。

要使nullptr起作用,您必须使用选项--std=c++11进行编译,因为它是 C++11 中的关键字,就像auto和 lambda 表达式语法一样。

gcc yourfile.cpp --std=c++11

但是关于delete,它只是第一行上一个被遗忘的分号。

C/C++ 要求使用分号分隔语句。

你应该写这样的东西:

Person** p = new Person*[5]; // A semi-colon was forgotten here.
// p is filled with five person pointer (say p[2] = *John where John is an object of person
// now we want to remove p[2]
delete p[2];
p[2] = p[3];
p[3] = p[4];
p[4] = nullptr;

另外,如果您不想为--std=c++11编译,请尝试使用0NULL而不是nullptr

p[4] = NULL;