首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

用C语言实现顺序栈时遇到的有关问题

2012-09-18 
用C语言实现顺序栈时遇到的问题编译可以过,执行不能过,代码如下:C/C++ code#include stdio.h#include s

用C语言实现顺序栈时遇到的问题
编译可以过,执行不能过,代码如下:

C/C++ code
#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); // 入栈}


[解决办法]
C/C++ code
#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;} 

热点排行