所以我在使用我的pop()函数时遇到了一个问题,当我第一次调用pop()函数时,它返回的项目没有问题,但是当它尝试连续弹出第二个项目,则失败。我似乎无法弄清楚为什么,在我的功能中是否有某些我想念的东西?PHP 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--];
}
它是如何失败?你可以添加输出吗?什么是'stack_item'? –
你应该检查大小的范围。提供更多的代码。 – moeCake
您可能会在断言失败,这意味着您的empty_stack函数可能有错误(返回false)。另一件需要考虑的是,您的stack_item *数据可能无法正确构建。发布错误以及如何填充和检查堆栈。 –