用printf检查错误,pop之前都是正确的,直到用while循环逐一pop出栈顶元素就出错了,只能正常输出第一个栈顶元素,之后移动指针再输出就不行了......求大佬指教!
#include<stdio.h>
#include<malloc.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
int* base;
int* top;
int stacksize;
}SqStack;
bool InitStack(SqStack &S){//InitStack
S.base=(int*)malloc(STACK_INIT_SIZE * sizeof(int));
if(!S.base)return false;
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return true;
}
bool Push(SqStack &S,int e){//逐个压栈
if(S.top-S.base>=S.stacksize) S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREMENT) * sizeof(int));
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
*S.top=e;
//printf("%d\t",*S.top);
S.top++;
return true;
}
int StackEmpty(SqStack S){
if(S.base==S.top)return 1;
//printf("非空");
return 0;
}
bool Pop(SqStack &S,int &e){
if(S.base==S.top)return false;
//删除栈顶元素,指针top减一
S.top--;
e=*S.top;
return true;
}
void main(){
int N=1348;
int e;
SqStack S;
InitStack(S);//创建栈S
printf("初始化成功");
while(N)
{
//printf("%d\t",N);
Push(S,N%8);//逐个压栈
N=N/8;
}
while(!StackEmpty(S)){//判断栈空
Pop(S,e);//逐个出栈
printf("%d",e);
}
fflush(stdin);
getchar();
}
结果;