我在分配任务时遇到了一些麻烦。我应该实现一个动态增长的堆栈,当它满时它的大小加倍,当它满 1/4 时它的大小减半。由于我是一个完全的 C 初学者并且不熟悉指针,因此我查看了一些示例,这就是我想出的代码。
它实际上在 gcc 中编译而没有警告,但是当我尝试运行它时会产生“分段错误”。我发现这可能与指针损坏有关,但我没有看到任何错误,如果有人可以为我指出,我会很高兴。
干杯
# ifndef STACK_H
# define STACK_H
# include "stdlib.h"
typedef struct stack {
int *stack;
int used;
int size;
} stack;
stack* stck_construct() {
stack *stck;
stck->stack = (int *)malloc(10 * sizeof(int));
stck->used = 0;
stck->size = 10;
return stck;
}
void stck_destruct(stack *stck) {
stck->stack = 0;
stck->used = stck->size = 0;
free(stck);
}
int stck_push(stack *stck, int val) {
if (stck->used == stck->size) {
stck->size *= 2;
stck->stack = (int *)realloc(stck->stack, stck->size * sizeof(int));
}
stck->stack[stck->used] = val;
stck->used++;
return 1;
}
int stck_pop(stack *stck, int *val) {
*val = stck->stack[stck->used];
free(stck->stack);
stck->used--;
if (stck->used <= (stck->size)/4) {
if (stck->size <=40) stck->size = 10;
else stck->size /= 2;
stck->stack = (int *)realloc(stck->stack, stck->size * sizeof(int));
}
return 1;
}
int main(){
stack* test;
test=stck_construct();
int i; int out;
for (i =1; i<=10; i++)
stck_push(test, i);
for (i =1; i<=10; i++) {
stck_pop(test,&out);
printf("%i\n", out);
}
stck_destruct(test);
return 0;
}
# endif