如何删除作为数组元素的指针

How to delete pointers that are elements of an array

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

下面是构造函数和析构函数的代码。析构函数成功销毁选项 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]