我正在尝试了解 Linux 内核链表 API。
根据 Linux Kernel Linked List我应该通过 INIT_LIST_HEAD
初始化列表头,但是 here (Linux Kernel Program)建议改用LIST_HEAD_INIT
。
这是我编写的有效代码,但我不确定我是否以正确的方式完成了它。有人可以验证它没问题吗?
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
typedef struct edge_attr {
int d;
struct list_head list;
} edge_attributes_t;
typedef struct edge {
int id;
edge_attributes_t *attributes;
} edge_t;
int main () {
int i;
struct list_head *pos;
edge_attributes_t *elem;
edge_t *a = (edge_t*)malloc(sizeof(edge_t));
a->id = 12;
a->attributes = (edge_attributes_t*) malloc(sizeof(edge_attributes_t));
INIT_LIST_HEAD(&a->attributes->list);
for (i=0; i<5; ++i) {
elem = (edge_attributes_t*)malloc(sizeof(edge_attributes_t));
elem->d = i;
list_add(&elem->list, &a->attributes->list);
}
list_for_each(pos, &(a->attributes->list)) {
elem = list_entry(pos, edge_attributes_t, list);
printf("%d \n", elem->d);
}
return 0;
}
最佳答案
LIST_HEAD_INIT
是一个静态初始化器,INIT_LIST_HEAD
是一个函数。他们都将 list_head
初始化为空。
如果你静态声明一个list_head
,你应该使用LIST_HEAD_INIT
,例如:
static struct list_head mylist = LIST_HEAD_INIT(mylist);
对于动态分配的列表头,通常是另一个结构的一部分,您应该使用 INIT_LIST_HEAD()
。内核源码中有很多例子。
关于c - LIST_HEAD_INIT 和 INIT_LIST_HEAD 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262017/