C++ 删除指针数组(C+;+;)中的元素
假设我有一个指针数组,比如C++ 删除指针数组(C+;+;)中的元素,c++,pointers,C++,Pointers,假设我有一个指针数组,比如 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; 除非删除delete和nullptr行,否则无法编译该程序。
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;
除非删除delete和nullptr行,否则无法编译该程序。
为什么会这样?如果我不删除p[2],应该会有问题,因为我无法再次访问john?如果您有这种模式,请使用
std::list
(或std::vector
)。标准容器将比您将提出的大多数解决方案更好。要使nullptr
工作,您必须使用选项--std=c++11
进行编译,因为它是c++11中的一个关键字,如auto
和lambda表达式语法
gcc yourfile.cpp--std=c++11
但是关于删除
,它只是第一行被遗忘的分号
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
,请尝试使用0
或NULL
而不是nullptr
p[4] = NULL;
请发布包含所有错误消息的邮件。您是如何为该数组安装
Person
实例的?除非删除delete和nullptr行,否则无法编译该程序。为什么?如果有错误,请将其作为文本添加到问题中。如果这是VisualStudio复制输出表中的错误而不是错误列表。我想关于代码> NulLPTR < /CUT>这是C++使用的标准,它应该是C++ 11使用<代码> NulLPTR < /Cord>哦,您似乎忘记了第一行中的半冒号,这就是为什么C++不能识别您的代码>删除/代码>作为另一个语句,如果不尝试在联机IDE上运行,我就无法知道这一点。不要使用new和delete以及数组,使用智能指针和std::vector。最好在std::list
之前使用std::vector
。但一般来说,我不是回答问题的朋友,他也可以使用