gpt4 book ai didi

c - PHP pop( ) 函数的问题

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:01 25 4
gpt4 key购买 nike

<分区>

所以我的 pop() 函数有问题,在运行我的程序时,我第一次调用 pop() 函数时它返回的项目没有问题,但是当它尝试连续弹出第二个项目时, 它失败。我似乎无法弄清楚为什么,我的功能中是否缺少某些东西?

#define DEFAULT_CAPACITY 16

struct stack {
size_t capacity;
size_t size;
stack_item *data;
};

stack *new_stack (void) {
stack *this = malloc (sizeof (stack));
assert (this != NULL);
this->capacity = DEFAULT_CAPACITY;
this->size = 0;
this->data = calloc (this->capacity, sizeof (stack_item));
assert (this->data != NULL);
return this;
}

void free_stack (stack *this) {
assert (empty_stack (this));
free (this->data);
free (this);
}

static bool full_stack (stack *this) {
return this->size == this->capacity;
}

static void realloc_stack (stack *this) {
size_t old_capacity = this->capacity;
this->capacity *= 2;
this->data = realloc (this->data, this->capacity);
memset (this->data + old_capacity, 0, old_capacity);
assert (this->data != NULL);
}


void push_stack (stack *this, stack_item item) {
if (full_stack (this)) realloc_stack (this);
//increase size of stack
this->data[this->size] = item;
this->size++;
}

stack_item pop_stack (stack *this) {
assert (! empty_stack (this));
printf("Stack size: %lu\n", this->size);
return this->data[this->size--];
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com