Reputation: 1
I'm currently working with stack data structure in C++, and i'm trying to initialize the stack by using arrays. Stack has a specific size and i want to print elements of the stack from top to bottom using for loop. Here is my code:
#include <iostream>
using namespace std;
template<class T>
class Stack {
private:
int top, size;
T* stack = new T[size];
public:
Stack(int size) {
this->top = -1;
this->size = size;
}
void push(int data) {
if (top >= size - 1) {
return;
}
else {
++top;
stack[top] = data;
}
}
void pop() {
if (top < 0) {
return;
}
else {
--top;
}
}
void print() {
for (int i = top; i >= 0; i--) {
cout << stack[i] << endl;
}
}
};
int main() {
Stack<int> stack(20);
stack.push(12);
stack.push(3);
stack.push(4);
stack.push(7);
stack.print();
return 0;
}
After compiling i get all of my elements printed successfully, but unfortunately at the end the program throws an exception ntdll.pdb not loaded. Thanks in advance.
Upvotes: 0
Views: 293
Reputation: 82461
The order of construction is wrong. The member variables are initialized before the constructor body is entered, so size
contains an arbitrary value at that time it's read to determine the size of the array. Furthermore you forgot to delete the array.
To fix the initialization order, initialize the array in the constructor and add a destructor. In the following code I simply use std::unique_ptr
which automatically deletes the array contained in it.
Furthermore it's preferrable to not use the same identifier for parameters and members; a prefix usually is added to member variables to avoid this
#include <memory>
...
template<class T>
class Stack {
private:
size_t m_size;
int m_top;
std::unique_ptr<T[]> m_stack;
public:
Stack(size_t size)
: m_stack(new T[size]), m_size(size), m_top(-1)
{
}
...
Upvotes: 1