0
我剛剛啓動了C++並編寫了一個程序,以同時在兩個堆棧中推送和彈出一個程序......我編寫了正確的代碼,但是當我運行該程序並嘗試訪問,即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);')來簡化一些函數。 –