c语言堆栈代码运行错误
答案:2 悬赏:30 手机版
解决时间 2021-04-08 00:55
- 提问者网友:战魂
- 2021-04-07 18:42
#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int status;
int elem,N,i,k,m;
#define OK 1
typedef struct{
int* top;
int* base;
int stacksize;
}sqstack;
sqstack *s;
s->base=NULL;
s->top=s->base;
void InitStack(sqstack*s){
s->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
}
status push(sqstack *s,int elem){
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)=elem;
++s->top;
return OK;
}
status pop(sqstack *s){
elem=*(s->top);
--(s->top);
return elem;
}
void main(){
InitStack(s);
}
为什么运行直接崩溃
最佳答案
- 五星知识达人网友:迟山
- 2021-04-07 20:04
sqstack *s;
s->base=NULL;
s->top=s->base;这里指针s还没分配空间就直接使用当然运行奔溃了,请看如下修改:#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int status;
int elem,N,i,k,m;
#define OK 1
typedef struct{
int* top;
int* base;
int stacksize;
}sqstack;
sqstack *s;
//s->base=NULL;
//s->top=s->base;缉弧光旧叱搅癸些含氓
void InitStack(sqstack* &s){ //这里改为指针引用,否则无作用
s = (sqstack *)malloc(sizeof(sqstack));//加了这句,先为s分配空间
s->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
}
status push(sqstack *s,int elem){
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)=elem;
++s->top;
return OK;
}
status pop(sqstack *s){
elem=*(s->top);
--(s->top);
return elem;
}
void main(){
InitStack(s);
}
s->base=NULL;
s->top=s->base;这里指针s还没分配空间就直接使用当然运行奔溃了,请看如下修改:#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int status;
int elem,N,i,k,m;
#define OK 1
typedef struct{
int* top;
int* base;
int stacksize;
}sqstack;
sqstack *s;
//s->base=NULL;
//s->top=s->base;缉弧光旧叱搅癸些含氓
void InitStack(sqstack* &s){ //这里改为指针引用,否则无作用
s = (sqstack *)malloc(sizeof(sqstack));//加了这句,先为s分配空间
s->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
}
status push(sqstack *s,int elem){
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)=elem;
++s->top;
return OK;
}
status pop(sqstack *s){
elem=*(s->top);
--(s->top);
return elem;
}
void main(){
InitStack(s);
}
全部回答
- 1楼网友:往事隔山水
- 2021-04-07 21:29
void initstack(sqstack **s)//传递的应该是指针的地址
{
if (*s = (sqstack *)malloc(sizeof(sqstack)))//判断下返回值
{
//malloc成功
*s->base=(int*)malloc(stack_init_size*sizeof(int));
*s->top=s->base;
*s->stacksize=stack_init_size;
}
}void main()
{
initstack(&s);//传递的应该是指针的地址
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯