我正在尝试构建一个通用函数来释放通用链表。我有几个结构体,我希望这个函数能够获取指向头部的指针,无论它的类型如何,并删除整个链表。
我怎样才能做到这一点?
减速是否应该是这样的:
void FreeLinkedList(void *first)
谢谢
最佳答案
如果保证在可能的struct
中没有指针成员,那么您可以使用下面的代码:
/*Actual structures definition*/
struct A{
struct A* next; // MUST be first element.
int some_data;
int some_other_data;
float some_more_data;
// int* pointer_to_some_other_data; // NOT allowed, if it is malloc'ed data, expected to be freed by your function.
int some_data_array[50]; // This is OK. array is part of the same struct. & it's different from pointer.
/*etc...*/
}
struct B{
struct B* next; // MUST be first element.
int some_other_data;
float some_more_data;
/*etc...*/
}
/*
struct C definition...
struct D definition...
etc
*/
/*Generic struct definition*/
struct generic_struct{
struct generic_struct* next; // MUST be first element. (It's the only element here.)
}
/*Generic free function*/
void FreeLinkedList(void *first){
if(first==NULL) return;
struct generic_struct *next=((struct generic_struct*)first)->next;
free(first); // assumes that there is no pointer data in struct_A or struct_B, except `next`.
FreeLinkedList(next);
}
//Usage:
FreeLinkedList(my_linked_list_head);
my_linked_list_head=NULL; // Don't MISS this. Alternately (& preferrably), you can change the `FreeLinkedList` function prototype to accept `void**` & do NULL assignment in the function.
注释:
- 传递给
FreeLinkedList
的链表必须包含堆
中的所有元素。如果某些元素来自 stack/global/static 则毫无意义 - 链表还可以混合使用
struct A
和struct B
成员。 - 结构体 A 和 B 不能有任何其他指针类型变量,这些变量可能已被
malloc
分配。否则,谁会释放
它? 下一个
元素必须是所有struct
中的第一个元素。
关于c - 释放C中的通用链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20660639/