0

This is from my .hpp file.

struct Item{
    std::string todo;};
const int MAX_STACK_SIZE = 5;
class StackArray
{
    public:
        StackArray();
        bool isEmpty();
        bool isFull();
        void push(std::string Item);
        void pop();
        Item* peek();
        int getStackTop() { return stackTop; }
        Item** getStack() { return stack; }
    private:
        int stackTop;
        Item* stack[MAX_STACK_SIZE];
};
#endif

And the following is part function from my .cpp file.

void StackArray::push(std::string Item)
{
    if (isFull())
    {
        cout<<"Stack full, cannot add new todo item."<<endl;
    }
    else
    {
        stackTop++;
        Item* newStack = new Item[MAX_STACK_SIZE];
        newStack[stackTop].todo = Item;
    }
}

I really confused about printing out the stack array in main.cpp file. How can I do that? Here is now I got, but can only print out the address.

int main()
{
    StackArray stackArray;
    if (stackArray.isEmpty())
        cout<< "Empty stack." <<endl;
    stackArray.push("25");
    stackArray.push("20");
    stackArray.push("15");
    stackArray.push("10");

    Item**stack1=new Item*[5];
    *stack1=new Item;
    stack1=stackArray.getStack();
    for(int i=0;i<5;i++)
    {
        cout<<*(stack1+i)<<endl;
    }
}
7
  • You're never saving newStack anywhere permanent, so you're leaking memory. Commented Oct 13, 2017 at 22:26
  • Why aren't you just adding the item to stack? Commented Oct 13, 2017 at 22:26
  • cout<<stack1[i]->todo; Except that it'll probably crash, because you never in fact initialize the contents of StackArray::stack; it contains random garbage. Commented Oct 13, 2017 at 22:28
  • using "cout<<stack1[i]->todo;" will get a seg fault. Commented Oct 13, 2017 at 22:32
  • Do I need to delete old stack after I assigned newStack in that function? Commented Oct 13, 2017 at 22:33

1 Answer 1

1

Your push method is never actually adding anything to the stack. It's allocating an entirely new array of pointers, but it's only assigned to a local variable, which goes away when the function ends. It should be adding the item to stack.

void TodoStackArray::push(std::string Item)
{
    if (isFull())
    {
        cout<<"Stack full, cannot add new todo item."<<endl;
    }
    else
    {
        stackTop++;
        stack[stackTop] = new Item;
        stack[stackTop]->todo = Item;
    }
}

To print out the items, you need to indirect through the pointers.

for (int i = 0; i < 5; i++) {
    cout << stack1[i]->todo << '\n';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.