So, I was working on a project where I needed to get a random object from a stack, so to make sure my design was correct, I made a dummy program that does nothing but fill a stack with data, then print it out. enter image description here
why in the world is nothing coming out of the stack but -1s??
Here's the stack.h file.
-
2Please do not put links to your code or worse, take screenshots of your code; the former makes your question NOT self-contained, the latter makes it extremely difficult to people who would be willing to help to actually try to, as they would have to retype everything from the screenshot!jfpoilpret– jfpoilpret2015年05月15日 16:22:47 +00:00Commented May 15, 2015 at 16:22
-
That's very true, I really should have just put it in tags. Very lazy of me, I apologize and will try to remember that for next time.Preston Shumway– Preston Shumway2015年05月15日 16:29:00 +00:00Commented May 15, 2015 at 16:29
2 Answers 2
You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.
class Stack
{
private:
int *p;
int top,length;
public:
Stack(int = 0); <<== CONSTRUCTOR - DEFAULT SIZE IS 0
~Stack();
void push(int);
int pop();
void display();
};
When you make your Stack object you must give it a size for the number of entries in the stack:
Stack stack(4);
You never allocate space for the stack.
The way it's written, you need to pass the stack size into the constructor, and then it's fixed for the lifetime of the object; i.e. it won't grow automatically when you call push()
. You're not passing anything into the Stack
constructor, so the parameter is defaulting to 0
, meaning it has zero size.
The solution is to declare the stack something like this:
Stack stack(10);
(10 is just an arbitrary size -- use whatever you expect to need.)
Incidentally, there isn't an effective safeguard in your code to handle an empty stack. The result is that you're technically getting undefined behaviour at the moment when you call push()
(it's writing to arbitrary memory locations).