用C语言实现顺序栈时遇到的问题
编译可以过,执行不能过,代码如下:
#include <stdio.h>#include <stdlib.h>typedef struct{ char *base; char *top; int stacksize;} SqStack;void InitStack(SqStack S){ char a[MAXSIZE]; S.base = a; if(!S.base) exit(0); S.top = S.base; S.stacksize = MAXSIZE;}// 入栈int Push(SqStack S, char e){ if(S.top - S.base == S.stacksize) return 0; // 栈满 *S.top++ = e; // 每次到这就出错,为什么?????? return 1;}void main(void){ char e = 'a'; SqStack S; InitStack(S); // 初始化栈 Push(S, e); // 入栈}
#include <stdio.h>#include <stdlib.h>#define MAXSIZE 10typedef struct{ char *base; char *top; int stacksize;} SqStack;void InitStack(SqStack *S){ S->base = (char *)malloc(sizeof(char) * MAXSIZE); if(!S->base) exit(0); S->top = S->base; S->stacksize = MAXSIZE;}// 入栈int Push(SqStack *S, char e){ if(S->top - S->base == S->stacksize) return 0; // 栈满 *(S->top++) = e; return 1;}int main(){ char e = 'a'; SqStack S; InitStack(&S); // 初始化栈 Push(&S, e); free(S.base); return 0;}