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.


  • 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! – jfpoilpret May 15 '15 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 May 15 '15 at 16:29

You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.

class Stack
    int *p;
    int top,length;

    Stack(int = 0);  <<== CONSTRUCTOR - DEFAULT SIZE IS 0

    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);
| improve this answer | |

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.