gpt4 book ai didi

谁能找到为什么解决后缀表达式的程序给出运行时错误

转载 作者:行者123 更新时间:2023-11-30 21:39:49 31 4
gpt4 key购买 nike

我试图解决后缀表达式,但我不明白为什么它会给出运行时错误。代码:

#include<stdio.h>

#include<stdlib.h>

#include<stdlib.h>

struct stack
{
int top;
int n[100];
}s;

void push(int a)
{
s.n[s.top+1]=a;
s.top++;
}

void pop(char a)
{
int c,b;
b=s.n[s.top];
c=s.n[s.top-1];

s.top--;

switch(a)
{
case '+':
s.n[s.top]=b+c;
break;

case '-':
s.n[s.top]=b-c;
break;

case '*':
s.n[s.top]=b*c;
break;

case '/':
s.n[s.top]=b/c;
break;
}
}

int main()
{
s.top=-1;
int m,i,k;

char a[100],c[100];

scanf("%d",&m);

for(i=0;i<m;i++)
{
int j=0;

while(1)
{
scanf("%c",a[j]);

if(a[j]=='?')
break;
else if(a[j]==' ')
{
push(atoi(a));
}
else if(a[j]=='+'||'-'||'*'||'/')
{
pop(a[j]);
}
else
{
j++;
}
}

printf("%d",s.n[s.top]);
}
}

最佳答案

你的代码很难可读,但我认为你需要改变

scanf("%c",a[j]);

scanf(" %c",&a[j]);  //note the space before %c, and scanf() expects pointer

对于

  1. & 因为根据 scanf() 签名,它需要地址来存储扫描结果。
  2. 前导空格 [] 以停止扫描之前按下的 ENTER [\n] 键。

请检查man page scanf() 了解更多详细信息。

另外,正如@LPs先生的回答中提到的,使用push(atoi(a));是非常危险的,万一a 不是以 null 结尾的。

关于谁能找到为什么解决后缀表达式的程序给出运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28338041/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com