我正在编写代码,将infix表达式转换为反向表示法,但我的程序正在执行该文件时崩溃。
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];
}在找到")“时返回弹出的操作符
int pop()
{
stack s;
int temp;
temp=s.a[s.top];
s.top--;
return temp;
}发布于 2015-03-24 10:23:02
在你的代码中
printf("%s",x[i]);是错的。你想要的是
printf("%c",x[i]);按照C11标准,第7.21.6.1章,%s格式说明符
如果不存在l长度修饰符,则参数应该是指向字符类型数组的初始元素的指针。..。
但是这里x[i]是char类型的。
另外,从第9段,
如果任何参数不是对应的转换规范的正确类型,则行为是未定义的。
因此,您的代码调用未定义行为。
接下来,对于push()和pop()这两个函数,您将定义一个局部变量stack s;该变量是在每次调用这些函数时创建的,并在完成执行时销毁。您可能需要使用gloabl变量来代替。删除局部变量,不需要它们。
另外,对于这两个函数,您都使用s.top值作为s.a数组的索引,但没有对其进行任何边界检查。在使用堆栈完整大小写(push())和堆栈空案例(pop())作为索引之前,您应该检查s.top的数组索引值。s.top的增量和减少也应放在检查项下。
编辑:
对于逻辑部分,在解析所有输入后,如果堆栈上还有任何要弹出的元素,则应该进行chcek。您应该打印堆栈包含,直到堆栈变为空,以获得完整的符号。请查看我下面的评论,以了解伪代码的概念。
注意:按照C标准,int main()应该是int main(void)
https://stackoverflow.com/questions/29229998
复制相似问题