1

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.

http://pastebin.com/vjhNLpNu

asked May 15, 2015 at 16:09
2
  • 2
    Please 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! Commented 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. Commented May 15, 2015 at 16:29

2 Answers 2

3

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);
answered May 15, 2015 at 16:16
0
1

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).

answered May 15, 2015 at 16:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.