mardi 24 juin 2014

Infix to Postfix absurd value


Vote count:

0




I have written a program below to convert Infix expression to Postfix expression.



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Stack{
int top;
int capacity;
char *array;
}Stack;

int isEmpty(Stack *s){
return s->top == -1;
}
char pop(Stack *s){
char c;
if(isEmpty(s))
return -1;
c = s->array[s->top];
s->array[s->top--] = '\0';
return c;
}

void push(Stack *s,char c){
s->array[++s->top] = c;
}

char peek(Stack *s){
return s->array[s->top];
}

char *toString(char c){
char *str = (char *)malloc(sizeof(char)*2);
str[0] = c;
str[1] = '\0';
return str;
}

int hasGreaterPriority(char c1,char c2){
if(c1 == '*' && (c2 == '+' || c2 == '-'))
return 1;
else if(c1 == '/' && (c2 == '+' || c2 == '-'))
return 1;
else
return 0;
}

void infixtopostfix(char exp[]){
int len = strlen(exp),i;
char *out = (char *)malloc(sizeof(char));
out[0] = '\0';

Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->capacity = len;
stack->top = -1;
stack->array = malloc(sizeof(sizeof(char)*len));

for(i=0; i<len; i++){
if(exp[i] >= 'a' && exp[i] <= 'z')
strcat(out,toString(exp[i]));
else if(exp[i] == ')'){
while(peek(stack) != '(')
strcat(out,toString(pop(stack)));
pop(stack);
}
else{
if(isEmpty(stack) || exp[i] == '(')
push(stack,exp[i]);
else if(hasGreaterPriority(peek(stack),exp[i])){
strcat(out,toString(pop(stack)));
push(stack,exp[i]);
}
else
push(stack,exp[i]);
}
}
/* UNTIL HERE */
while(!isEmpty(stack))
strcat(out,toString(pop(stack)));

strcat(out,"\0");
printf("Postfix Expression: %s\n",out);
}

int main(void) {
char exp[] = "a+b*(c/d-e)/(f+g*h)-i\0";
printf("Infix Expression: %s\n",exp);
infixtopostfix(exp);
return 0;
}


Problem is as follows:


In infixtopostfix method, prior to while indicated by "UNTIL HERE" out variable value seems to be correct. I checked with the help of gdb. After 2 iterations of while loop also the value in out variable seems to be fine. In the last iteration i.e. while adding + into out,the value becomes as follows



abcd/e-fgh*+/i-*\377\377\377\377\025+


How did \377\377\377\377\025+ get added to out variable?


Expected value would be abcd/e-fgh*+/i-*+



asked 55 secs ago






Aucun commentaire:

Enregistrer un commentaire