中缀以反转波兰符号

时间:2015-03-24 10:20:55

标签: c data-structures stack rpn

我正在编写一个代码来将中缀表达式转换为反向表示法,但我的程序在执行文件时崩溃

typedef struct stack
 {
   char a[400];
   int top;
 }
 stack;
 stack s;
 void push(char *,int);
 int pop();

 int main()
  {
    char x[400];
    int len,i,y;
    puts("Enter string");
    scanf("%s",x);
    len=strlen(x);
    for(i=0;i<len;i++)
      {
//considering user is entering only the small alphabets 

      if((x[i])>=97&&x[i]<=122)
      printf("%s",x[i]);

      else
//if encountering the operator then pushing it into stack

      if(x[i]=='/'||x[i]=='*'||x[i]=='+'||x[i]=='-')
        {
        push(x,i);
        }

      else if(x[i]=='(')
      continue;
//When encountering the ')' then popping the operator

      else
        {
        y=pop();
        printf("%c",y);
        }
    }

  return 0;
 }

传递数组及其大小作为参数

void push(char *x,int i)
{
  stack s;
  s.top++;
  s.a[s.top]=x[i];
}

返回弹出的操作符,找出&#34;)&#34;

int pop()
 {
   stack s;
   int temp;
   temp=s.a[s.top];
   s.top--;
   return temp;
 }

1 个答案:

答案 0 :(得分:1)

在您的代码中

printf("%s",x[i]);

错了。你想要的是

printf("%c",x[i]);

根据C11标准,章7.21.6.1%s格式说明符

  

如果不存在l length修饰符,则参数应为 指向初始值的指针   字符数组 的元素。 ...

但此处x[i]的类型为char

另外,从第9段开始,

  

如果有任何论据   不是相应转换规范的正确类型,行为是   未定义。

因此,您的代码会调用undefined behaviour

接下来,对于这两个函数push()pop(),您要定义一个局部变量stack s;这是在每次调用这些函数时创建的,并在完成执行时销毁。您可能希望使用gloabl变量。删除局部变量,不需要它们。

此外,对于这两个函数,您使用s.top值作为s.a数组的索引,但不对其进行任何边界检查。在使用push()值作为索引之前,应检查堆栈完整案例(pop())的数组索引值和堆栈空案例(s.top)。 s.top的增量和减量也应放在支票下面。


编辑:

对于逻辑部分,在解析所有输入之后,如果堆栈上还有任何元素要弹出,则应该chcek。你应该打印堆栈包含,直到堆栈变空为止,以获得完整的符号。请查看下面的评论,了解伪代码的概念。


注意:根据C标准,int main()应为int main(void)

相关问题