创建链表,插入数据至链表尾,将链表内嵌至其他数据结构.,contain_of找到结构体成员所在的结构体
#ifndef _LIST_H
#define _LIST_H
#define contain_of(ptr, type, member) \
((type *)((size_t)ptr - (size_t) & (((type *)0)->member)))
typedef struct node
{
struct node *next;
struct node *prev;
} node_t;
typedef struct list
{
node_t head;
} list_t;
void list_init(list_t *list);
void list_insert(list_t *list, node_t *node);
#endif /* _LIST_H */
#include "list.h"
void list_init(list_t *list)
{
list->head.next = list->head.prev = &list->head;
}
void list_insert(list_t *list, node_t *node)
{
node_t *end_node = list->head.prev;
end_node->next = node;
node->prev = end_node;
node->next = &list->head;
list->head.prev = node;
}
#include "list.h"
#include <string.h>
typedef struct user_data
{
char name[10];
int id;
node_t node;
} user_data_t;
list_t user_data_list;
user_data_t data[2] = {0};
static void user_data_init(user_data_t *u_d)
{
u_d->node.next = (void *)0;
u_d->node.prev = (void *)0;
memset(u_d->name, 0, 10);
u_d->id = 0;
}
static void user_data_to_list(list_t *list, node_t *node)
{
list_insert(list, node);
list_insert(list, node);
}
void user_data_init_all()
{
for (int i = 0; i < 2; i++)
{
user_data_init(&data[i]);
user_data_to_list(&user_data_list, &(data[i].node));
}
}
void increase_data_id(user_data_t *data)
{
data->id++;
}
user_data_t *temp_data = 0;
int main()
{
list_init(&user_data_list);
user_data_init_all();
increase_data_id(&data[1]);
increase_data_id(&data[1]);
temp_data = contain_of((data[0].node.next), user_data_t, node);
while (1)
{
}
return 0;
}