Printing a stack

Hello everyone. I am just started learning c++. In the code here, I try to print the stack, but getting a segmenmentation fault. Any help appreciated, thanks in advance.



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
template <class T>
void Stack<T>::print() const
{
  Stack szymek=*this;
  for(int i=size-1;i--;i>-1)
  {
  cout << szymek.items[i] << cout << endl;
  }
}
 // related stack part:
private:
        T* items;
        size_t size;
        size_t capacity;

//and my copy constructor:

template <class T>
Stack<T>::Stack(const Stack<T>& rhs)
{
  items = new T[rhs.capacity]; 
  size = rhs.size;
  capacity = rhs.capacity;

  for (int i=0;i++;i<size)
  {
  	items[i] = rhs.items[i];
  }
}
Last edited on
Check the for loops. The increment/decrement and the condition to stop the loop seem to have been reversed. If the code ends up going beyond the bounds of the items array into memory it shouldn't access, that might cause a segmentation fault.

The for loop is designed to iterate a number of times. Its syntax is:

for (initialization; condition; increase) statement;


http://www.cplusplus.com/doc/tutorial/control/
print() is trying to print a different stack. It made a copy of itself at line 4.

remove line 4 and remove "szymek." from line 6.
Thank you guys, now it is in this form.
It prints now., with a slight problem. For example, it should print "4", but it prints "40x544645".
What do you guys think the problem is?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template <class T>
void Stack<T>::print() const
{
 if (size!=0)
  {
  for(int i=size-1;i>-1;i--)
  {
  cout << items[i] << cout << endl;
  }
}
}

template <class T>
void Stack<T>::printReversed() const
{
 if (size!=0)
  {
  for(int i=0;i<size;i++)
  {
  cout << items[i] << cout << endl;
  }
}
}
Because you have an array of pointers, so you are printing the memory address not the value that is stored there.
1
2
std::cout<< *items[i]; //prints value stored at the memory address
std::cout<< items[i]; //prints memory address 
Last edited on
I don't think that is the case. It gives an error when I write it this way: *items[i].

its printing the 4, followed by the address of the cout object, because you tried to serialise that also.

cout << items[i] << cout << endl;
should be
cout << items[i] << endl;
Topic archived. No new replies allowed.