简体   繁体   English

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

[英]How to delete pointers that are elements of an array

Below is the code for constructor and destructor. 下面是构造函数和析构函数的代码。 Destructor successfully destructs the array created by option 1. What if we have multiple array as in option 2. Will the same destructor coding is enough to delete or some changing in the code is required. 析构函数成功地解构了由选项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??
}

Your int *input[3] is a raw array that will contain pointers to ints, aka int* . 您的int *input[3]是一个原始数组,其中将包含指向int的指针,也就是int* You have a lot of errors in your code, for example you are accessing the 4th position of the array top with top[3] , which has just 3 elements, and you are assigning something { -1 } to its imaginary 4th element, instead of an int. 您的代码中有很多错误,例如,您使用top[3]访问数组top的第4个位置,该位置只有3个元素,而您为其虚构的第4个元素分配了{ -1 }一个整数。

These declarations are also not valid, because you are using the same identifier for 2 different variables: 这些声明也是无效的,因为您为2个不同的变量使用了相同的标识符:

int *input;//option1        
int *input[3];//option 2

If you want to delete the memory allocated by an array of pointers, I would iterate through the array calling each time delete [] on them: 如果要删除由指针数组分配的内存,则每次对它们的delete []调用时,我都要遍历该数组:

for(int i=0; i<3; i++)
     delete [] input[i];

This is going to free all the memory allocated by the pointer to integers input[0] , input[1] and input[2] . 这将释放指针分配给整数input[0]input[1]input[2]所有内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM