Not getting any compile error, but I'm getting an output that looks like:
-858993460 5 4 3 2

Instead of 5 4 3 2 1. What am I doing wrong?

#include <iostream>
#include <stack>
using namespace std;
template <typename T>
void reverse(stack<T> &sk)
{
	stack<int> tempStack;
	while(!sk.empty())
	{
		tempStack.push(sk.top());
		sk.pop();
	}
	sk = tempStack;
}

int main()
{	
	
	int arr[] = {1,2,3,4,5};
	int arrSize = sizeof(arr)/sizeof(int);
	stack<int> intStack;

	for(int i = arrSize; i>0; i--)
	{
	intStack.push(arr[i]);
	}

	reverse(intStack);
	while(!intStack.empty())
	{
		cout << intStack.top() << " ";
		intStack.pop();
	}
	return 0;
}

Not getting any compile error, but I'm getting an output that looks like:
-858993460 5 4 3 2

Instead of 5 4 3 2 1. What am I doing wrong?

#include <iostream>
#include <stack>
using namespace std;
template <typename T>
void reverse(stack<T> &sk)
{
	stack<int> tempStack;
	while(!sk.empty())
	{
		tempStack.push(sk.top());
		sk.pop();
	}
	sk = tempStack;
}

int main()
{	
	
	int arr[] = {1,2,3,4,5};
	int arrSize = sizeof(arr)/sizeof(int);
	stack<int> intStack;

	for(int i = arrSize; i>0; i--)
	{
	intStack.push(arr[i]);
	}

	reverse(intStack);
	while(!intStack.empty())
	{
		cout << intStack.top() << " ";
		intStack.pop();
	}
	return 0;
}

Problem lies within the main program, in the condition of the for loop where values are being push to the intStack.

WRONG:

for(int i = arrSize; i>0; i--)
	{
	intStack.push(arr[i]);
	}

in the first loop you are trying to access array location which is yet to be initialized.

correct code would have been,

for(int i = arrSize-1 ; i> -1; i--)
	{
	intStack.push(arr[i]);
	}

Oh, no wonder. So the first value that it was printing was just the address of arr[5], right?

Thank you!

I think it's not the address, but some uninitialized garbage value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.