I’m fairly new to C++ and new to pointers as well. I’m currently working on a stack and was trying to reallocate the memory for the stack as the size of the stack reaches the top however, I’m running into issues. I’ve already done a lot of research both on Google and stack overflow and have found some information helpful but since I’m so new to stacks and C++ I’m still having issues. I was hoping some bright and intelligent people could at least point me in the right direction.
now… Here’s my code.
#include <iostream>
#define STACKMAX 20
using namespace std;
template <class T> class StackTemplated {
private:
int top;
T values[STACKMAX];
public:
StackTemplated();
void push(T i);
T pop(void);
bool empty(void);
};
template <class T> StackTemplated<T>::StackTemplated() {
top = -1;
}
template <class T>void StackTemplated<T>::push(T i) {
if (top == STACKMAX - 1) {
// reallocate top of stack. (this is the area I'm having issues)
char * string1;
string1 = (char *)calloc(STACKMAX, sizeof(char));
if (top == STACKMAX - 1) {
cout << "The stack didn't re-allocate.";
exit(1);
}
} else {
top++;
values[top] = i;
}
}
template <class T> T StackTemplated<T>::pop(void) {
if (top < 0) {
printf("%", "Stack underflow!");
exit(1);
} else {
return values[top--];
}
}
template <class T> bool StackTemplated<T>::empty() {
return (top == -1);
}
The problem is that you don’t want to reallocate the top of the stack. Rather, you want to allocate a new array of values which is large enough to hold the new values. Also, since you need to reallocate the array,
valuesshould be a pointer.But how about we forget all this. If we’re working in c++, let’s use what c++ offers us to make our lives easier. After that’s done, then try open things up, if you really feel the need.
One of the things I’m referring to is your use of
calloc. Usingcallocis a bad idea, particularly when using templates. The problem is that sincecallochas no type information, it won’t do something as basic as calling a constructor. Constructors are very important in OOP, since they guarantee that an object’s invariance when it is created. Instead, use thenew[]keyword, likeThis allocates an array of
TofSTACKMAXlength. Of course, as Greg points out, you should reconsider the use ofSTACKMAX, and use a variable instead. Also,valuesshouldn’t be a static array, but should instead have typeT*.Another thing I was referring to is the fact that you are really trying to implement an array which grows dynamically as needed. In c++, we call such a structure a
vector. If you use a vector, your entire code reduces toThat’s all. It’s a lot less hairy if you can use an existing data structure to implement the new data structure.
Once you get really comfortable with how a
vectorworks (and there’s plenty of explanations / documentation on the web), then try implementing the functionality yourself. Bottom line is, implementing a data structure is a lot easier if you know exactly how it’s supposed to behave.