Reputation: 647
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.
#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??
}
Upvotes: 0
Views: 96
Reputation: 15837
Your int *input[3]
is a raw array that will contain pointers to ints, a.k.a 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.
These declarations are also not valid, because you are using the same identifier for 2 different variables:
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:
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]
.
Upvotes: 1