Generally, the logic of your code is OK except a return value mistake in the empty()
function.
In the empty()
, it should return 1 while stack is empty.
int empty(){
if(top==-1)
return(0); <-- !!! here should return 1
}
Otherwise,
- it will go into the while loop at
while(precedence(value)<=precedence(stack[top])&&!empty())
even when stack is empty. - And then
postfix[j] = x
may write a redundant0
(now top= -2) topostfix
array. - Finally,under the input
2+3
, thepostfix[]
will be{'2','\0','3','+',...}
, which result in the abnormal output2
.
So, it will work after modifying the empty()
function, such as
int empty()
{
if(top==-1)
return(1); // not return(0)
return(0);
}
Output:
Enter an infix expression
2+3
23+
solved Not able to figure out the logical error in my code