내 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 * 데이터가 올바르게 구성되지 않았을 수 있습니다. 오류를 게시하고 스택이 채워지고 검사되는 방법을 게시하십시오. –