顺序栈的初始化代码好像有问题

#include #include /* run this program using the console pauser or add your own getch, system("pause") or input loop */#define MAXSIZE 100typedef int SElemType;typedef int Status;typedef struct{ SElemType *base; SElemType top; int stacksize;}SqStack;Status InitStack(SqStack S){ S->base=(SElemType)malloc(MAXSIZEsizeof(SElemType)); if(!S->base) return 0; S->top=S->base; S->stacksize=MAXSIZE; return 1;}Status Push(SqStack *S,SElemType e){ if(S->top-S->base==S->stacksize) return 0; *(S->top)++=e; return 1;}SElemType GetTop(SqStack *S){ if(S->top!=S->base) printf("11"); return *(S->top-1);}int main(int argc, char *argv[]) { SqStack *s; //printf("--"); printf("%d",InitStack(s)); Push(s,3); printf("%d",GetTop(s)); return 0;}

修改如下,供参考:

#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define MAXSIZE 100
typedef int SElemType;
typedef int Status;
typedef struct{ 
    SElemType *base; 
    SElemType top; 
    int stacksize;
}SqStack;
Status InitStack(SqStack*& S) //修改
{
    S = (SqStack*)malloc(sizeof(SqStack));  // 修改
    S->base = (SElemType*)malloc(MAXSIZE * sizeof(SElemType));
    if (!S->base) return 0;
    S->top = 0;  //S->base; 修改
    S->stacksize = MAXSIZE;
    return 1;
}
Status Push(SqStack *S,SElemType e)
{ 
    if (S->top == S->stacksize)  //(S->top-S->base==S->stacksize)修改
        return 0; 
    S->base[S->top++] = e;      //*(S->top)++=e; 修改
    return 1;
}
Status Pop(SqStack* S, SElemType* e) //修改
{
    if (S->top == 0) {
        *e = -1;
        return 0;
    }
    *e = S->base[--S->top];
    return 1;
}
SElemType GetTop(SqStack *S)
{ 
    if (S->top == 0) //(S->top!=S->base)修改 
    {
        printf("11\n");
        return -1;       //修改
    }
    return  S->base[S->top - 1]; //*(S->top-1);修改
}
int main(int argc, char *argv[]) 
{ 
    SqStack *s; 
    SElemType e;
    
    printf("%d\n",InitStack(s)); 
    printf("--\n");
    Push(s, 3); 
    Push(s, 5);
    Push(s, 7);
    printf("%d\n",GetTop(s)); 

    Pop(s, &e);
    printf("%d\n", e);
    Pop(s, &e);
    printf("%d\n", e);
    Pop(s, &e);
    printf("%d\n", e);
    Pop(s, &e);
    printf("%d\n", e);
    return 0;
}