字符串输入后程序崩溃

时间:2016-12-20 12:19:10

标签: c algorithm

我的程序基本上将中缀表达式转换为后缀表达式,尽管到目前为止我的程序只接受单个数字。无论如何,当我尝试编译时,在输入我的中缀表达式之后,程序几乎立即崩溃。我的代码:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int priority(char x); // Determines priority of incoming operator.
void push(char x); // Pushes element to stack.
char pop(); // Pops element from stack.

char stack[10];
int top = -1;

int main() {
char init[20];
printf("Enter an expression: ");
fgets(init, 20, stdin);
int x = 0, y, z = 0;
static char result[20];
while (init[x++] != '\0') {
    if (isalnum(init[x]))
        result[z++] = init[x]; // Operand printed out immediately.
    else if (init[x] == '(')
        push(init[x]); // '(' character pushed.
    else if (init[x] == ')') {
        while ((y = pop()) != '(')// Popping elements from stack until reaching '('
            result[z++] = y;
    } else if (init[x] == ' ') {
        z++;
    else {
        while (priority(init[x]) <= priority(stack[top])) // If expression operator has higher precedence than stack operator, expression operator is pushed onto stack. Else stack operator is popped and printed out.
            result[z++] = pop();
        push(init[x]);
    }
}
while (top != -1)
    result[z++] = pop(); // Remaining operators printed out.
printf("Final expression is %s.\n", result);
}
int priority(char x) {
    int precedence = 0;
    if(x == '(')
        precedence = 0;
    if(x == '+' || x == '-')
        precedence = 1;
    if(x == '*' || x == '/')
        precedence = 2;
    if(x == '^')
        precedence = 3;
    return precedence;
}

void push(char x) {
stack[++top] = x;
}

char pop() {
return stack[top--];
}

我有一个版本可以使用但是当我看这个版本时,似乎没有任何不同。有人可以告诉我我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

我发现的一个主要问题是:

while (init[x++] != '\0') 在循环的条件检查中增加x的值时,再次尝试在调用函数时访问它:

isalnum(init[x])

第一个数字永远不会以这种方式评估。因此,如果您输入&#34; 5 + 2&#34;,只有&#34; + 2&#34;将被评估,这是一个无效的中缀表达式。