我很好奇如何删除存储在列表中的结构。 我尝试了这段代码,但它给了我一个段错误错误,而且我看不到错误。
typedef struct double_stack_head_struct
{
struct double_stack_head_struct* tail;
double value;
} double_stack_head;
typedef struct double_stack_struct // the structure containing the state of a stack
{
int size; // size of stack
double_stack_head* head;
} double_stack;
void push_double_stack(double_stack* stack, double value)
{
double_stack_head* new_head = malloc(sizeof(double_stack_head));
if(new_head != NULL) {
new_head->tail = stack->head;
new_head->value = value;
stack->head = new_head;
stack->size += 1;
}
}
int pop_double_stack(double_stack* stack, double* value)
{
if(empty_double_stack(stack)) {
return false;
} else {
*value = stack->head->value;
free(stack->head);
stack->size -= 1;
stack->head = malloc(sizeof(stack->head));
stack->head = stack->head->tail;
return true;
}
}
最佳答案
请记住,malloc
和 free
应该彼此对称,因为对于给定的 malloc
调用,在堆,应该有一个匹配的 free
调用来释放它。
如果我们只看一下您的堆栈逻辑,您的推送函数会分配一个新节点。您的 pop 函数释放一个节点,但它也分配一个新节点。所以我们这里有一些不对称的东西,这将是一个问题。
另外需要注意的是,sizeof(struct Node*)
与 sizeof(struct Node)
不同。当您执行 sizeof(stack->head)
时,您实际上是在检查 size->head
类型的大小,这是指针的大小,而不是被指者。
但是,您实际上并不希望在 pop 函数中分配新节点,因此您需要更正堆栈逻辑。当您从这样的单链表中弹出时,您想要捕获指向头节点(堆栈顶部)的指针,将头设置为指向下一个元素(堆栈顶部的正下方),并释放那个前头。
关于c - free() struct** 指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30413860/