gpt4 book ai didi

c - 为什么每当我在表达式中输入括号时,以下代码都会显示段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:50 25 4
gpt4 key购买 nike

代码:

#include<stdio.h>
#include<ctype.h>
#define MAX 100

typedef struct stack
{
char data[MAX];
int top;
}stack;

void push(stack *s, char c)
{
s->top++;
if(s->top>MAX)
{
printf("Stack Overflow\n");
return;
}
s->data[s->top]=c;

}

int isEmpty(stack *s)
{
if(s->top==-1)
return 0;
else
return 1;
}

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

void pop(stack *s)
{
printf("%c ", s->data[s->top]);
s->top--;
}

void infixToPostfix(stack *s)
{
int c;
printf("Enter an expression\n");
while((c=getchar()) != '\n')
{
if(isalnum(c))
printf("%c ", c);
else
{
if(c=='(')
push(s, c);
else if(c==')')
{
while(c != '(')
pop(s);
pop(s);
}
else
{
while((priority(c) <= priority(s->data[s->top])) && isEmpty(s))
{
pop(s);
}
push(s, c);
}
}
}
while(s->top)
{
pop(s);
}
pop(s);
}

int main(void)
{
stack s;
s.top=-1;
infixToPostfix(&s);
return 0;
}

出于某种奇怪的原因,每当输入表达式中有括号时,我都会遇到段错误。我的目标是将中缀表达式转换为后缀表达式。我试图使用堆栈来实现它。

是因为我将堆栈从一个被调用的函数传递给其他函数吗?

最佳答案

        else if(c==')')
{
while(c != '(')
pop(s);
pop(s);
}

如果 c 是一个 ),它就不可能是一个 ( 直到你改变它的值。在那个 while 循环,你不会改变它的值。所以这将永远调用 pop

void pop(stack *s)
{
printf("%c ", s->data[s->top]);
s->top--;
}

此函数没有安全性。如果您在堆栈为空时pop,它将读取到s->data 的边界之外。所以在无限循环中调用 pop 是一场灾难。

关于c - 为什么每当我在表达式中输入括号时,以下代码都会显示段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42983864/

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