C语言版数据结构——栈的初始化有关问题

C语言版数据结构——栈的初始化问题
不知为什么,程序一运行就异常停止。求大神帮看看哪里不对啊!!
#define FLASE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKCREMENT 10
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType * base;
SElemType * top;
int stacksize;
}SqStack;
//////////////////////////////////////////////
Status InitStack(SqStack *S);
Status Push(SqStack *S, SElemType e);
Status Pop(SqStack *S, SElemType *e);
void Print(SqStack *S);
//////////////////////////////////////////////
void main()
{
int N = 4;
SqStack *S;
InitStack(S);//初始化一个栈
Push(S,5); //放一个数字5进去
Print(S); //看看能不能输出来

}
Status InitStack(SqStack *S) //初始化一个空栈
{
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base)exit(OVERFLOW);
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack *S, SElemType e)//压栈操作
{
if(S->top - S->base >= S->stacksize)
{
S->base = (SElemType *)malloc((S->stacksize + STACKCREMENT) * sizeof(SElemType));
if(!S->base)exit(OVERFLOW);
S->top = S->base + S->stacksize;//
S->stacksize += STACKCREMENT;
}
printf("xx");//debug
*(S->top) = e;
printf("%d",*(S->top));
S->top++;
return OK;
}
Status Pop(SqStack *S, SElemType *e)//出栈
{
if(S->base == S->top)return ERROR;
*e = *(S->top);
--S->top;
return OK;
}
void Print(SqStack *S)//打印
{
int *p;
p=S->base;
if(S->base == S->top)
{
printf("\n空栈!没有数据用来输出!\n");
exit(FLASE);
}
else
{
printf("%d");
p++;
}
}
数据结构 c语言 malloc

------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

在发生问题后,看一下在哪儿断住的


S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
这一句断掉了


s 初始化了吗?
我没搞懂啊。C语言版数据结构——栈的初始化有关问题但是书上就是这么干的啊。。。请问要怎么初始化,S指向谁呢,我就是想初始化S,InitStack()函数就是用来初始化S的啊。。。C语言版数据结构——栈的初始化有关问题


把你的书扔了吧。
S没有初始化,居然就S->base
看来你可以这样试试:
void main()
{
    int N = 4;
    SqStack S;
    InitStack(&S);//初始化一个栈
    Push(&S,5);    //放一个数字5进去
    Print(&S);    //看看能不能输出来
 
}
------解决方案--------------------

Status Push(SqStack *S, SElemType e)//压栈操作
{
    if(S->top - S->base >= S->stacksize)
    {
        S->base = (SElemType *)malloc((S->stacksize + STACKCREMENT) * sizeof(SElemType));
        if(!S->base)exit(OVERFLOW);
        S->top = S->base + S->stacksize;//
        S->stacksize += STACKCREMENT;        
    }
    printf("xx");//debug
    *(S->top) = e;
    printf("%d",*(S->top));
    S->top++;
    return OK;
}

改成

Status Push(SqStack *S, SElemType e)//压栈操作
{
#define USE_REALLOC 1
    if(S->top - S->base >= S->stacksize)
    {
        //申请一块更大的内存
#if USE_REALLOC
        // realloc 重新申请更大内存。会自动搬迁数据。
       
        SElemType * p  =(SElemType *)realloc(S->base,(S->stacksize + STACKCREMENT) * sizeof(SElemType));
        if( !p ){ free(S->base); exit(OVERFLOW);}