如何删除作为数组元素的指针
How to delete pointers that are elements of an array
下面是构造函数和析构函数的代码。析构函数成功销毁选项 1 创建的数组。如果我们有多个数组,如选项 2 中所示怎么办。相同的析构函数编码是否足以删除或需要对代码进行一些更改。
#include "iostream"
class Mystack
{
private:
int capacity;
int top[3];
int *input;//option1
int *input[3];//option 2
public:
Mystack();
~Mystack();
void push(int stackNum, int elem);
void pop(int stackNum);
void display();
};
Mystack::Mystack()
{
capacity = 3;
top[3] = { -1 };
input[] = new int[capacity]; //option 1
input[3] = new int[capacity];// option 2
}
Mystack::~Mystack()
{
delete[]input;// Works for option 1. Should it be same for option 2??
}
您的int *input[3]
是一个原始数组,其中包含指向整数(又名int*
)的指针。您的代码中有很多错误,例如,您正在使用 top[3]
访问数组顶部的第 4 个位置,它只有 3 个元素,并且您正在为其虚构的第 4 个元素分配一些{ -1 }
的东西,而不是 int。
这些声明也是无效的,因为您对 2 个不同的变量使用相同的标识符:
int *input;//option1
int *input[3];//option 2
如果要删除指针数组分配的内存,我会在每次delete []
指针时遍历数组调用:
for(int i=0; i<3; i++)
delete [] input[i];
这将释放指针分配给整数的所有内存 input[0]
、 input[1]
和 input[2]
。
相关文章:
- 从指向结构数组的指针中提取元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 使用指针访问数组元素时出现意外结果
- 指针数组.获取指针元素的值
- 指向数组的指针是否应该等于指向其第一个元素的指针?
- 如何理解取消引用指向数组的指针会获取指向元素的指针
- 如何使用指针更改数组元素
- 通过指针访问数组元素
- C 中的动态数组(用指针表示) - 输入元素
- 字符指针对象和相应的字符数组元素比较
- 无法访问指向数组的指针的元素
- 指向数组的指针会更改数组元素的值
- C++如何使用指针来循环移位数组元素
- 从 C++ 数组元素的指针获取索引的最快方法是什么
- 当我删除数组时,指针在哪里?指向数组的指针与数组中的元素之间的区别
- 从C++中的指针访问数组元素
- 数组元素值,元素地址和指针增量
- 返回指向指针数组的指针获取下一个元素失败
- 数组的指针,该数组的每个元素的内存空间信息存储在哪里