核心list.h在使用者態使用舉例
阿新 • • 發佈:2019-02-13
1. list的定義
struct list_head
2.引用方法{ struct list_head *next, *prev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name) static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; }
在結構體重包含struct list_head,該結構體可位於任何欄位,一個結構體中可以包含多個struct list_head.
struct mylist
{
void *data;
struct list_head use;
struct list_head free;
};
3. 根據list變數獲取結構體
#define list_entry(ptr, type, member) \ container_of(ptr, type, member) #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #define container_of(ptr, type, member) ({\ const typeof( ((type *)0)->member ) *__mptr = (ptr);\ (type *)( (char *)__mptr - offsetof(type,member) );})
例如,struct list_item結構如下
struct list_item
{
void *data;
struct list_head list;
};
struct list_head *pos;
struct list_item *p = list_entry(pos, struct list_item, list);
p即為結構體指標。
4. 操作舉例
struct list_item { int id; struct list_head list; }; int main() { struct list_item *tmp; struct list_head *pos, *p; int i; //定義成員 struct list_item mylist; //初始化連結串列 INIT_LIST_HEAD(&mylist.list); for(int i = 0; i < 5; i++) { tmp = (list_item*)malloc(sizeof(struct list_item)); tmp->id = i; list_add(&tmp->list, &mylist->list); } //遍歷 list_for_each(pos, &mylist.list) { tmp = list_entry(pos, struct list_item, list); printf("id = %d\n",tmp->id); } }