当我使用 gets()
或 fgets()
而不是 scanf()
时,程序会完全执行但会打印段错误(核心倾倒)到底!我不明白为什么我在这两种情况下都会遇到段错误。下面是使用堆栈将中缀转换为后缀 exp 的代码。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct stack{
int top;
int capacity;
int *array;
}stack;
stack* createstack(char *);
void push(stack* ,int );
int isempty(stack *);
int pop(stack *st);
int peek(stack *st);
int precedence(char c);
int main(){
char exp[100];
char post[100];
int k=-1;
stack *st;
int i=0,p=0;
printf("enter string expression: ");
//gets(exp);
//fgets(exp, sizeof(exp), stdin);
scanf("%s",exp);
printf("Infix expression : %s",exp);
st=createstack(exp);
for(i=0;i<strlen(exp);i++){
if( (exp[i]>='a' && exp[i]<='z') || (exp[i]>='A' && exp[i]<='Z'))
post[++k]=exp[i];
else if(exp[i]=='(')
push(st,exp[i]);
else if(exp[i]==')'){
while(!isempty(st) && peek(st)!='(')
post[++k]=pop(st);
pop(st);
}
else{
while(precedence(exp[i]) < precedence(peek(st)))
post[++k]=pop(st);
push(st,exp[i]);
}
}
while(!isempty(st))
post[++k]=pop(st);
//post[++k]='\0';
printf("Postfix expression :\n%s\n",post);
return 0;
}
stack* createstack(char *exp){
stack* st;
st->top=-1;
st->capacity=strlen(exp);
st->array=(int*)malloc(st->capacity * sizeof(int));
printf("Stack created successfully\n");
return st;
}
void push(stack* st,int val){
st->array[++st->top]=val;
}
int isempty(stack *st){
return st->top==-1;
}
int pop(stack *st){
return st->array[st->top--];
}
int peek(stack *st){
return st->array[st->top];
}
int precedence(char c){
switch(c){
case '(':
return 0;
break;
case '+':
return 1;
break;
case '-':
return 1;
break;
case '*':
return 2;
break;
case '/':
return 2;
break;
case '^':
return 3;
break;
}
}
最佳答案
在你的代码中,
stack* st;
st->top=-1;
您正在使用 st
未初始化,这又会调用 undefined behaviour .
使用前需要给st
分配内存。
尝试类似的东西
stack* st = malloc(sizeof*st); //also, check for malloc success
也就是说,
请see why not to cast
malloc()
和C
中的 family 的返回值。main()
的推荐签名是int main(void)
。
关于c - 使用 scanf 时程序立即终止并出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931798/