2017-04-03 47 views
0
#include <stdio.h> 
#include <ctype.h> 

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

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

char pop() 
{ 
    if(top==-1) 
     return -1; 
    else 
     return stack[top--]; 
} 

此功能用于优先运营商:这个程序将中缀转换为c中的后缀给出了运行时错误。为什么?

int priority(char x) 
{ 
    if(x=='+'|| x=='-') { 
     return 1; 
    } else if(x=='(') { 
     return 0; 
    } else if(x=='*'||x=='/') { 
     return 2; 
    } else { 
     return 3; 
    } 
} 

int main() 
{ 
    char exp[50], *e, x; 
    scanf("%s", exp); 
    e = exp; 
    while(*e != '\0') { 
     if(isalnum(*e)) { 
      printf("%c",*e); 
     } else { 
      while(priority(stack[top]) >= priority(*e)) { 
       printf("%c",pop()); 
      } 
      push(*e); 
     } 
     e++; 
    } 
    while(top!=-1) { 
     printf("%c",pop()); 
    } 
    return 0; 
} 

我在这个节目得到一个运行时错误。我不知道为什么。你能告诉我任何可以实施的改变吗?在一些编译器中,我将输出看作一些无限循环。

+0

你会得到哪个错误? – Gianluca

+0

尝试使用调试器查看出错的位置。 –

回答

0

该代码被执行

while(priority(stack[top])>=priority(*e)) 

首次top-1所以你访问stack[-1]。这不是合法的访问,您的程序可能会崩溃。

如果程序没有崩溃,你会得到一些“随机”值,你传递给priority。现在您将此“随机”字符的优先级与输入的第一个字符的优先级进行比较。我们假设比较结果为真。然后你执行:

printf("%c",pop()); 

由于top-1,该pop功能不会改变top,使其保持在-1。然后,你再这样做:

while(priority(stack[top])>=priority(*e)) 

由于两个top*e没有改变,比较将再次导致如此。换句话说 - 无尽的循环。

相关问题