中缀到Prefix转换,分段错误

时间:2016-10-07 10:34:33

标签: c

我试图将给定的中缀表达式转换为前缀。但是我得到了一个分段错误,核心转储错误。它与使用"得到"有关。 (我得到警告,使用它是危险的)或if优先级和isOperator fucntion中的if语句?我认为我的逻辑是正确的,所以你能否告诉我我做错了什么?谢谢你。

#include <stdio.h>
#include <string.h>
#define MAX 50
char stack[MAX];
int top=-1;
void reverse(char array[MAX]){
    int i,j;
    char temp[MAX];
    for(i=strlen(array)-1,j=0;i>=0;i--,j++){
        temp[j]=array[i];
    }
    temp[j]='/0';
    strcpy(array,temp);
}
char pop(){
    return stack[top--];
}
void push(char ele){
    stack[++top]=ele;
}
int isOperator(char ele){
    if(ele=="+"||ele=="-"||ele=="*"||ele=="^"||ele=="/"||ele=="#"||ele=="("||ele==")"){
        return 1;
    }
    else{
        return 0;
    }
}
int precedence(char ele){
    if(ele=="+"||ele=="-"){
        return 2;
    }
    if(ele=="("||ele=="("||ele=="#"){
        return 1;
    }
    if(ele=="*"){
        return 3;
    }
    if(ele=="/"){
        return 4;
    }
    if(ele=="^"){
        return 5;
    }
}
void infixToPrefix(char infix[MAX],char prefix[MAX]){
    int i,j=0;
    reverse(infix);
    char symbol;
    stack[++top]="#";
    for(i=0;i<strlen(infix);i++){
        symbol=infix[i];
        if(isOperator(symbol)==0){
            prefix[j]=symbol;
            j++;
        }
        else{
            if(symbol==")"){
                push(symbol);
            }
            else if(symbol=="("){
                while(stack[top]!=")"){
                    prefix[j]=pop();
                    j++;
                }
                pop();//to remove the bracket 
            }
            else{
                if(precedence(symbol)<=precedence(stack[top])){
                    push(symbol);
                }
                else{
                    while(precedence(symbol)>=precedence(stack[top])){
                        prefix[j]=pop();
                        j++;
                    }
                    push(symbol);
                }
            }
        }
    }
    while(stack[top]!="#"){
        prefix[j]=pop();
        j++;
    }
    prefix[j]="\0";
}
int main(){
    char infix[MAX],prefix[MAX];
    gets(infix);
    infixToPrefix(infix,prefix);
    reverse(prefix);
    puts(prefix);
    return 0;
}

0 个答案:

没有答案
相关问题