运行输出时,好象出现了越界的一个值。(经其他原码改编)
怎么会。。。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 10
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define SIZE 5
typedef char SElemType;
typedef int Status;
typedef struct STACK /*define a stack*/
{
Status *base;
Status *top;
int stacksize;
int length;
}SqStack,*Stack;
void InitStack(Stack *S) /*give value*/
{
*S=(SqStack *)malloc(sizeof(SqStack));
(*S)->base=( Status *)malloc(STACK_INIT_SIZE*sizeof(Status));
if(!(*S)->base)
exit(-1);
(*S)->top=(*S)->base;
(*S)->stacksize=STACK_INIT_SIZE;
(*S)->length=0;
}
Status DestroyStack(Stack *S) /* destroy stack*/
{
free((*S)->base);
free((*S));
return OK;
}
void ClearStack(Stack *S) /*make the stack become empty*/
{
(*S)->top=(*S)->base;
(*S)->length=0;
}
Status StackEmpty(SqStack S) /*if empty?*/
{
if(S.top==S.base) return TRUE;
else
return FALSE;
}
void Push(Stack *S, Status e) /*enter stack:*/
{
if((*S)->top - (*S)->base>=(*S)->stacksize)
{
(*S)->base=(Status *) realloc((*S)->base,
((*S)->stacksize + 4) * sizeof( Status));
if(!(*S)->base) exit(-1);
(*S)->top=(*S)->base+(*S)->stacksize;
(*S)->stacksize += 4;
}
*((*S)->top++)=e;
++(*S)->length;
}
Status Pop(Stack *S) /*go outside:*/
{
Status fruit;
if((*S)->top==(*S)->base) return ERROR;
fruit=*((*S)->top);
(*S)->top--;
--(*S)->length;
return fruit ;
}
Status GetTop(Stack S, Status *e)/*return the first element*/
{
if(S->top==S->base) return ERROR;
*e=*(S->top-1);
S->top--;
}
main()
{
int a[20], i, j;
Stack s;
InitStack(&s);
printf("Input some nums please(within 5):\n");
for(i=0; i<SIZE; i++)
{
scanf("%d", &a[i]);
Push(&s, a[i]);
}
for(i=0; i<SIZE ; i++)
{
if (!StackEmpty(*s))
j=Pop(&s);
printf("%2d\n", j);
printf("\n");
}
DestroyStack(&s);
}