Miscellaneous doubt

I was trying to submit the code for stock span problem and i found out that if in the while loop if i put any other condition before checking stack is empty it gives me a runtime error whereas for the same code if i put the stack empty before any other condition it doesnt give the run time error. Can someone tell me why is this so?
//Code of run time error

#include
#include
using namespace std;
int main() {
int n;
cin >> n;
int A[n];
for(int i=0;i<n;i++)
cin>>A[i];
int ans[n];
ans[0]=1;
stack st;
st.push(0);
for(int i=1;i<n;i++)
{
while((A[i] >= A[st.top()]) && (!st.empty()))
{
st.pop();
}
if(st.empty())
{
ans[i]=i+1;
}
else
{
ans[i] = i - st.top() ;
}
st.push(i);
}
for(int i=0;i<n;i++)
{cout<<ans[i]<<" ";}
cout<<“END”<<endl;

return 0;

}

//Correct code

#include
#include
using namespace std;
int main() {
int n;
cin >> n;
int A[n];
for(int i=0;i<n;i++)
cin>>A[i];
int ans[n];
ans[0]=1;
stack st;
st.push(0);
for(int i=1;i<n;i++)
{
while((!st.empty()) && (A[i] >= A[st.top()]))
{
st.pop();
}
if(st.empty())
{
ans[i]=i+1;
}
else
{
ans[i] = i - st.top() ;
}
st.push(i);
}
for(int i=0;i<n;i++)
{cout<<ans[i]<<" ";}
cout<<“END”<<endl;

return 0;

}