【发布时间】:2021-07-23 01:56:39
【问题描述】:
我使用教程编写了这段代码。他的输出是正确的,但我得到了 stackoverflow 和内存地址作为输出,虽然我的代码和他的完全一样。我已经声明了数组大小 100,但它仍然不起作用
#include<iostream>
using namespace std;
#define n 100
class stack{
int* arr;
int top;
public:
stack(){
arr=new int[n];
top=-1;
};
void push(int x){
if(top=n-1){
cout<<"Stack overflow"<<endl;
return;
}
top++;
arr[top]=x;
};
void pop(){
if(top==-1){
cout<<"No element to pop"<<endl;
return;
}
top--;
};
int Top(){
if(top==-1){
cout<<"Stack is empty"<<endl;
return -1;
}
return arr[top];
};
bool empty(){
return top==-1;
}
};
int main(){
stack st;
st.push(1);
st.push(2);
st.push(3);
cout<<st.Top()<<endl;
st.pop();
cout<<st.Top()<<endl;
st.pop();
st.pop();
st.pop();
cout<<st.empty()<<endl;
return 0;
}
【问题讨论】:
-
这看起来像是一个完美的调试器练习。
-
或调整编译器的练习,我无法编译此代码:godbolt.org/z/Krx1fnGPW
-
无意冒犯,但几乎每次有人说“完全一样”时,它不是;)
标签: c++ data-structures stack