I’m trying to write a program that evaluates a postfix arithmetic expression. The program sends a character string to my function evaluatePostfix, which proceeds to identify operands and operators and come up with an integer solution. I am manipulating stacks in this program by pushing the scanned character as it is identified and of course doing the appropriate pop functions when needing to evaluate. Right now though, I’m having a problem with the program hanging in what appears to be an infinite loop. I guess I’m not really sure how to tell the function to proceed to the next character in the string after it has evaluated the first character. Another thing to note is that the user puts a space in-between each operand and operator. Here is my function:
int evaluatePostfix(char *postfixStr)
{
stack * s;
int x, y;
stackInit(&s);
do {
if(isOperand(postfixStr) == 1) {
stackPush(&s, postfixStr);
}
if(isOperator(postfixStr) == 1) {
y = atoi(stackPop(s));
x = atoi(stackPop(s));
char *str = malloc(10 * sizeof(char));
sprintf(str, "%d", applyOperator(x, y, postfixStr));
stackPush(&s, str);
}
} while (postfixStr != NULL);
return stackPop(s);
}
I know the functions that manipulate the stack are correct as they were provided by my instructor. Could someone perhaps give me a clue as to what I’m missing?
You could change the
whilecondition towhile (++postfixStr != NULL)to increment the pointer to the next character inpostfixStr.This increment is done using the prefix notation (
++varvsvar++) so that the next character is compared toNULL. I’m not familiar with the behavior of the stack functions you’re using, but I would recommend changing thedo { ... } while (++postfixStr != NULL);loop to awhile (postfixStr != NULL) { ... }loop, and incrementpostfixStrat the end of that while loop’s block.The safest thing to do is add a string length parameter to your function:
You would then use a loop that explicitly steps from the beginning of the string at index
0to indexstrLength - 1, which would safely handle empty and non-NULL-terminated strings.