所以我在使用我的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 *數據可能無法正確構建。發佈錯誤以及如何填充和檢查堆棧。 –