Why is my program not printing the elements of the stack

It prints addresses instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
    using namespace std;

  class Stack{


    private:
        struct node
      {
            int value;
            node *next;

            node(int value, node *next = NULL)
            {
                this->value = value;
                this->next = next;
            }
        };

    public:
  node *top;
    //node top();
        Stack()
        {
            top = NULL;
        }
        void push(int number)
        {
            top = new node(number, top);
        }
  //node *top;

        int pop()
        {
            int number = top->value;
            node *temp = top;
            top = top->next;
            delete temp;

            return number;
        }
       bool isEmpty() {
    return (top == NULL);
}

    };

    int main() {
        Stack s;
        Stack temp;

        s.push(5);
        s.push(7);
        s.push(8);
        temp = s;

      cout<<"stack elements: "<< endl;
        while(!temp.isEmpty())
        {
            cout <<temp.top<<" ";
            temp.pop();
        }
        cout<< endl<<"The top element of stack:" <<endl<< s.top<<endl;

        return 0;
    }
s.top and temp.top are node pointers. So cout << is printing out the address of this pointer.
You need to access the actual value of the node, which is its .value.

Edit: As lastchance pointed, out, I meant top->value, not top.value.
Last edited on
1
2
3
4
            cout <<temp.top->value<<" ";
            temp.pop();
        }
        cout<< endl<<"The top element of stack:" <<endl<< s.top->value<<endl;
temp.top is a function.

temp.top() is how to call that function. You probably meant to call the function.
temp.top is a pointer. (In this instance. But, to be fair, my first reaction was the same as @Repeater's.)
Last edited on
Pointer. I must confess (like lastchance) I didn't even read the class. The error simply jumps out as a common error; accessing something as a memory address instead of actually intended data.
Last edited on
So, @bopaki, please don't confuse us!
http://www.cplusplus.com/reference/stack/stack/top/
It would be simpler to just use the return value from pop:
1
2
3
while (!temp.Empty()) {
    cout << temp.pop() << ' ';
};


temp = s; Now temp and s share the same stack data. If you pop an item from one, the other is left with a dangling pointer.

Thank you all !!!!
Using the arrow operator yielded the desired output.
 
  top->value
Topic archived. No new replies allowed.