我试图实现用C进行堆栈。这是我的代码,我运行了代码,代码结尾为:
线程1:EXC_BAD_ACCESS错误
我很困惑,不知道出了什么问题,有人可以调试代码吗?谢谢!
还有一个问题,为什么 command + k 键对我不起作用?我必须逐行缩进。
#include <stdio.h>
#include <stdlib.h>
#define init_size 10
#define increment 1
typedef struct sqStack
{
int* top;
int* base;
int stack_size;
} sqStack;
int init_stack(sqStack* sq)
{
if(sq->base==NULL)
{
sq->base = (int*)malloc(init_size*sizeof(int));//Thread 1: EXC_BAD_ACCESS
}
if(sq->base==NULL) exit(-1);
sq->stack_size=init_size;
sq->top=sq->base;
return 1;
}
int push(sqStack* sq, int e)
{
if(sq==NULL) exit(-1);
if(sq->top-sq->base==sq->stack_size)
{
int* q = (int*)realloc(sq->base,
(init_size+increment)*sizeof(int));
if(q==NULL) exit(-1);
else
{
sq->base=q;
sq->stack_size += increment;
sq->top=sq->base+sq->stack_size;
}
*sq->top++=e;
}
return 1;
}
int pop(sqStack* sq,int*e)
{
if(sq==NULL) exit(-1);
if(sq->base==sq->top) exit(-1);
sq->top-=1;
*e=*sq->top;
return 1;
}
int empty(sqStack* sq)
{
if(sq->base==sq->top) return 1;
else return 0;
}
int main()
{
sqStack* sq=NULL;
init_stack(sq);
push(sq,1);
int *e=(int*)malloc(sizeof(int));
pop(sq,e);
printf("%d\n",*e);
return 0;
}
答案 0 :(得分:1)
int init_stack(sqStack* sq)
中
if(sq->base==NULL)
{
sq->base = (int*)malloc(init_size*sizeof(int));//Thread 1: EXC_BAD_ACCESS
}
应为:
sq->base = (int*)malloc(init_size*sizeof(int));//Thread 1: EXC_BAD_ACCESS
int push(sqStack* sq, int e)
}
*sq->top++=e;
}
return 1;
}
应该是
}
}
*sq->top++=e;
return 1;
}
int main()
无需使用int *e=(int*)malloc(sizeof(int));
,只需使用int e;
sqStack* sq=NULL;
init_stack(sq);
push(sq,1);
int *e=(int*)malloc(sizeof(int));
pop(sq,e);
printf("%d\n",*e);
应该是
sqStack sq;
init_stack(&sq);
push(&sq,1);
int e;
pop(sq,&e);
printf("%d\n",e);
以下code
可以工作:
#include <stdio.h>
#include <stdlib.h>
#define init_size 10
#define increment 1
typedef struct sqStack {
int* top;
int* base;
int stack_size;
} sqStack;
int init_stack(sqStack* sq) {
sq->base = (int*)malloc(init_size * sizeof(int));
if (sq->base == NULL) exit(-1);
sq->stack_size = init_size;
sq->top = sq->base;
return 1;
}
int push(sqStack* sq, int e) {
if (sq == NULL) exit(-1);
if (sq->top - sq->base == sq->stack_size) {
int* q = (int*)realloc(sq->base, (init_size + increment) * sizeof(int));
if (q == NULL)
exit(-1);
else {
sq->base = q;
sq->stack_size += increment;
sq->top = sq->base + sq->stack_size;
}
}
*sq->top++ = e;
return 1;
}
int pop(sqStack* sq, int* e) {
if (sq == NULL) exit(-1);
if (sq->base == sq->top) exit(-1);
sq->top -= 1;
*e = *sq->top;
return 1;
}
int empty(sqStack* sq) {
if (sq->base == sq->top)
return 1;
else
return 0;
}
int main() {
sqStack sq;
init_stack(&sq);
push(&sq, 1);
int e;
pop(&sq, &e);
printf("%d\n", e);
return 0;
}