【发布时间】:2017-05-19 02:14:16
【问题描述】:
我刚刚启动 c++ 并编写了一个程序以在一个程序中同时推送和弹出 2 个堆栈....我正确地编写了它但是当我运行程序并尝试访问第一个堆栈即 s1 它显示分段错误但是我可以非常完美地访问我的第二个堆栈 s2 .....帮帮我
#include<iostream>
using namespace std;
#define max 10
class stack
{
private:
int arr[max],top;
public:
void init()
{
int top=0;
}
void push(int a)
{
arr[top++]=a;
}
int pop()
{
return arr[--top];
}
int isempty()
{
if(top==0)
return 1;
else
return 0;
}
int isfull()
{
if(top==max)
return 1;
else
return 0;
}
};
int main()
{
int a,z,cas;
stack s1;
stack s2;
s1.init();
s2.init();
while(1)
{
cout<<"Enter your choice i.e. :\n";
cout<<"1.Pushing in stack s1.\n";
cout<<"2.Pushing in stack s2.\n";
cout<<"3.Poping from stack s1.\n";
cout<<"4.Poping from stack s2.\n";
cout<<"5.To STOP.\n";
cin>>cas;
switch(cas)
{
case 1:
cout<<"Enter the number to push in stack s1:\n";
cin>>a;
if(s1.isfull()==0)
s1.push(a);
else
cout<<"The Stack is full.\n";
break;
case 2:
cout<<"Enter the number to push in stack s2:\n";
cin>>a;
if(s2.isfull()==0)
s2.push(a);
else
cout<<"The Stack is full.\n";
break;
case 3:
if(s1.isempty()==0)
cout<<"The number poped out is :\n"<<s1.pop()<<endl;
else
cout<<"The stack is empty.\n";
break;
case 4:
if(s2.isempty()==0)
cout<<"The number poped out is :\n"<<s2.pop()<<endl;
else
cout<<"The stack is empty.\n";
break;
case 5:
cout<<"The elements in stack s1 are :\n";
while(!s1.isempty())
cout<<s1.pop()<<" ";
cout<<endl;
cout<<"The elements in stack s2 are :\n";
while(!s2.isempty())
cout<<s2.pop()<<" ";
cout<<endl;
exit(1);
}
}
return 0;
}
【问题讨论】:
-
由于您“刚刚开始使用 C++”,因此您应该花时间使用调试器。调试器允许您一次执行每个语句(也称为单步)并查看变量的值。
-
由于您使用的是 C++,因此请使用带有
true和false值的bool类型。使用 1 和 0 是一种古老的做法(大约在 1960 年代或更早)。 -
您可以通过将比较放在
return语句中来简化一些函数,例如return (top == max);。 -
另外,将
stack重命名为std::stack已在使用中,并且您已通过using namespace std;允许来自std命名空间的每个符号。 -
在您的
push方法中,您需要在推送元素之前检查堆栈是否已满。否则,您正在访问数组之外,这会导致 Undefined Behavior (任何事情都可能发生)。同样,您需要在弹出元素之前检查堆栈是否为空。
标签: c++ c++11 data-structures segmentation-fault stack