请问我这个在运行到主函数第一个if里的push函数时为什么会出错
补充:之后做了其他题,就在这代码上修改,但有关堆栈使用的函数没改,也同样运行不了
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct num
{
int size;
int *top,*base;
};
char ch;
int f()
{
int x=0;
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
printf("%c\n",ch);
}
printf("%d\n",x);
return x;
}
void build(struct num *s)
{
s=(struct num*)malloc(sizeof(struct num));
s->base=(int*)malloc(100*sizeof(int));
if(!s->base)exit(-2);
s->top=s->base;
s->size=100;
printf("1\n");
}
int pop(struct num *s)
{
int data;
s->top--;
data=*(s->top);
return data;
}
void push(int data,struct num *s)
{
if ((s->top) - (s->base) >= (s->size))
{
s->base = (int *)realloc(s->base,(s->size + 100)*sizeof(int));
if (!s->base) exit(-2);
s->top = s->base + s->size;
s->size += 100;
}
*(s->top)=data;
(s->top)++;
return;
}
int check(struct num *s)
{
if(s->top==s->base)return 0;
return 1;
}
int main()
{
struct num *sn,*sp;
build(sp);
build(sn);
while((ch=getchar())!='\n')
{
printf("%c\n",ch);
if((ch>='0'&&ch<='9')||ch=='+'||ch=='-'||ch=='/'||ch=='*'||ch=='('||ch==')')
{
printf("%c\n",ch);
if(ch>='0'&&ch<='9')
{
push(f(),sn);
printf("%c\n",ch);
}
else if(!check(sp))
{
push((int)ch,sp);
}
else if(ch=='+'||ch=='-')
{
if(check(sp)&&(*(sp->top-1)=='+'||*(sp->top-1)=='-'||*(sp->top-1)=='*'||*(sp->top-1)=='/'))
{
while(check(sp)&&*(sp->top-1)!=')')
{
char c;
c=pop(sp);
int x=pop(sn),y=pop(sn);
switch(c)
{
case '+':
y+=x;
break;
case '-':
y-=x;
break;
case '*':
y*=x;
break;
case '/':
y/=x;
break;
}
push(y,sn);
}
}
push((int)ch,sp);
}
else if(ch=='/'||ch=='*')
{
if(check(sp)&&(*(sp->top-1)=='*'||*(sp->top-1)=='/'))
{
while(*(sp->top-1)=='*'||*(sp->top-1)=='/')
{
char c0;
c0=(char)pop(sp);
int x=pop(sn),y=pop(sn);
switch(c0)
{
case '+':
y+=x;
break;
case '-':
y-=x;
break;
case '*':
y*=x;
break;
case '/':
y/=x;
break;
}
push(y,sn);
}
}
push((int)ch,sp);
}
else if(ch==')')
{
while(*(sp->top-1)!='(')
{
char c0;
c0=(int)pop(sp);
int x=pop(sn),y=pop(sn);
switch(c0)
{
case '+':
y+=x;
break;
case '-':
y-=x;
break;
case '*':
y*=x;
break;
case '/':
y/=x;
break;
}
push(y,sn);
}
pop(sp);
}
else
{
push((int)ch,sp);
}
}
}
while(check(sp))
{
char c0;
c0=(int)pop(sp);
int x=pop(sn),y=pop(sn);
switch(c0)
{
case '+':
y+=x;
break;
case '-':
y-=x;
break;
case '*':
y*=x;
break;
case '/':
y/=x;
break;
}
push(y,sn);
}
printf("%d",*(sn->base));
return 0;
}
网上搜搜一大把,比如:
https://www.csdn.net/tags/MtzaYgysMDIwOTUtYmxvZwO0O0OO0O0O.html