dimanche 23 octobre 2016

Thereh is no build error in code but it terminates ,displaying segmentation fault (core dumped) after i give the prefix expression

This is a program to convert prefix to postfix expression:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

here i used an array of strings in my stack:

struct oprndstack
{
int top;
char item[10][10];
}op;

class abc
{
public:
abc(){op.top=-1;}

i passed strings in my functions pop and push:

void push (char *x)
{if(op.top==9)
{cout<<"stack overflow";}
else
{op.top=op.top+1;
strcpy(op.item[op.top],x);
}
}
char* pop()
{if(op.top==-1)
{cout<<"stack underflow";}
else
{char *x;
strcpy(x,op.item[op.top]);
op.top=op.top-1;
return x;
}}
};
int main()    
{ abc st; char e[10]; char operand1[10];char operand2[10]; char value[20];
cout<<"enter the prefix expression";
cin>>e;
int len;
len=strlen(e);
for(int i=len-1;i>=0;i--)
{ char symb[1];
symb[0]=e[i];

if symb is an operand i directly push it into stack:

if ((symb[0]<=122)&&(symb[0]>=97))
{st.push(symb);}

if the symb is an operator i pop the stack in operand1 AND OPERAND2 than concartenate them in order operand1,operand2,symb and push it back into stack:

else
{
strcpy(operand1,st.pop());
strcpy(operand2,st.pop());
strcat(operand1,operand2);
strcat(operand1,symb);
strcpy(value,operand1);
st.push(value);
}
}
cout<<"the expression postfix is";
cout<<st.pop();
cout<<endl<<value;
}

Aucun commentaire:

Enregistrer un commentaire