Evaluating a postfix Expression in C

丶灬走出姿态 提交于 2019-12-25 02:35:31

问题


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?


回答1:


You could change the while condition to while (++postfixStr != NULL) to increment the pointer to the next character in postfixStr.

This increment is done using the prefix notation (++var vs var++) so that the next character is compared to NULL. I'm not familiar with the behavior of the stack functions you're using, but I would recommend changing the do { ... } while (++postfixStr != NULL); loop to a while (postfixStr != NULL) { ... } loop, and increment postfixStr at the end of that while loop's block.

The safest thing to do is add a string length parameter to your function:

int evaluatePostfix(char *postfixStr, int strLength)

You would then use a loop that explicitly steps from the beginning of the string at index 0 to index strLength - 1, which would safely handle empty and non-NULL-terminated strings.



来源:https://stackoverflow.com/questions/9346409/evaluating-a-postfix-expression-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!