This is my program to convert an expression from postfix to infix using stacks. I am getting no errors but on running, the compiler says Segmentation Fault - Core Dumped. I think it has something to do with a pointer pointing to a garbage value. How do I tracebck to this rogue pointer? Also, is there any better method to convert postfix to infix?
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
class StringStack
{
public:
char arr[20][20];
int top;
StringStack()
{top=-1; arr[20][20]={NULL};}
void push(char* a)
{strcpy(arr[++top],a);}
char* pop()
{return arr[top--];}
};
void paranthesise(char a[])
{
int l = strlen(a);
a[l+2] = '\0';
for(int i=l; i>=0; i++)
a[i] = a[i-1];
a[0] = '(';
a[l+1] = ')';
}
using namespace std;
int main()
{
char temp[1];
char postfix[20] = "";
char temp2[10] = "";
char temp3[10] = "";
StringStack s1;
cout<<"Enter Postfix Expression: "<<endl;
gets(postfix); int l = strlen(postfix);
for(int i=0; i<l; i++)
{
if(postfix[i]!='*'&&postfix[i]!='/'&&postfix[i]!='+'&&postfix[i]!='-')
{
temp[0]=postfix[i];
s1.push(temp);
}
else
{
strcpy(temp2,s1.pop());
strcpy(temp3,s1.pop());
switch(postfix[i])
{
case'*':
temp[0]='*'; break;
case'/':
temp[0]='/'; break;
case'+':
temp[0]='+'; break;
case'-':
temp[0]='-'; break;
default: cout<<"Error"; break;
}
strcat(temp3,temp);
strcat(temp3,temp2);
paranthesise(temp3);
s1.push(temp3);
}
}
strcpy(temp2,s1.pop());
cout<<"\nInfix:";
puts(temp2);
return 0;
}