源码如下:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACK_INCREAMENT_SIZE 10
typedef char ElemType;
typedef struct {
ElemType *base;
ElemType *top;
int stack_size;
}STACK,*STACK_PTR;
void init_stack(STACK *s)
{
s = (STACK_PTR)malloc(sizeof(STACK));//写了结构体指针,需要分配一个结构体内存才能使用该指针
s->base = (ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(s->base == NULL)
{
printf("stack initial failed");
exit(0);
}
s->top = s->base;
s->stack_size = STACK_INIT_SIZE;
}
void push(STACK *s,ElemType e)
{
/* if(s->top - s->base >= s->stack_size)
{
//printf("now\n");
s->base = (ElemType *)realloc(s->base,(s->stack_size + STACK_INCREAMENT_SIZE)*sizeof(ElemType));
if(!s->base)
{
exit(0);
}
s->stack_size = s->stack_size + STACK_INCREAMENT_SIZE;
}*/
printf("s->top is %d \n",s->top);
s->top++;
}
ElemType pop(STACK *s)
{
return (s->base == s->top) ? -1 : *(--s->top);
}
int get_stack_len(STACK *s)
{
return s->top - s->base;
}
int main()
{
STACK_PTR s;
init_stack(s);
for(int i =0 ; i < 10 ; i++)
{ printf("%d pushed \n",i+1);
push(s,(ElemType)i);
}
return 0;
}
我将36行37行屏蔽掉,可以正常运行,即屏蔽:
push函数中的:
printf("s->top is %d \n",s->top);
s->top++;
因此十分确定是访问成员top指针时出现的错误.....现在一头雾水 不知道啥情况。求大家帮忙解决一下。