i just started c++ and coded a program to push and pop in 2 stacks simultaneously inn a program....i coded it corectly but while i run the program and try to access the first stack i.e s1 it shows segmentation fault but i am able access my second stack s2 very perfectly.....help me
#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;
}
booltype withtrueandfalsevalues. Using 1 and 0 is an ancient practice (like around 1960's or earlier).returnstatement, such asreturn (top == max);.stackasstd::stackis already in use and you have allowed every symbol from thestdnamespace byusing namespace std;.pushmethod, you need to check for stack full before pushing an element. Otherwise, you are accessing beyond the array, which causes Undefined Behavior (anything could happen). Similarly, you need to check for stack empty before popping elements.