runtime error

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
#include "bits/stdc++.h"
#include<stack>
using namespace std;
int main()
{
	while(true)
	{
		int n;
		cin>>n;
		int a[n];
		stack<int> st;
		if(n==0)break;
		else		
		{
			for(int i=0;i<n;i++)
			{
				cin>>a[i];
			}
		 
		 int count=1;
		 for(int i=0;i<n;i++)
		 {
		 	st.push(a[i]);
			 while(st.top()==count)
		 	{
		 	count++;
			 st.pop();	
			}
//			st.push(a[i]);
		 }
		 if(st.size()==0)
		 {
		 	cout<<"yes\n";
		 }
		 else cout<<"no\n";
	    }    
	}
}


WEll what is the error in this code.I am not able to figure out..It is showing runtime error.
Last edited on
I see two problems.

Firstly, in C++, a variable length array ( int a[n]; ) is forbidden.

Secondly, on line 24, you call top on an empty stack. This is bad. Do not do this. First check that the stack isn't empty, and only then call top on it.
Last edited on
I'm surprised this even compiles.

1
2
cin>>n;
int a[n];


This doesn't work in c++. The size of an array must be constant at compile time.
You can only do it that way if you allocate memory on the heap for it.

1
2
cin>>n;
int *a = new int[n];


But you'll have to use delete so you don't get memory leak - http://www.cplusplus.com/doc/tutorial/dynamic/

The best thing to do, is to just use std::vector - http://www.cplusplus.com/reference/vector/vector/vector/
Well i got the mistake in the stack which you mentioned .But there is no problem in the array because i have taken the input of variable n then i have defined the array a.
thanks
It's still illegal in C++. Your compiler is letting you create a variable length array. It shouldn't. It's illegal. It's not C++. It's incorrect C++. Your compiler might let you do it, but it shouldn't. You shouldn't write incorrect code just because the compiler you're happening to use right now happens to let you.
Okk !!thanks for the advice @Moschops
Topic archived. No new replies allowed.