container_of > 编程 > c_cpp



* container_of - cast a member of a structure out to the containing structure
* @ptr:     the pointer to the member.
* @type:     the type of the container struct this is embedded in.
* @member:     the name of the member within the struct.
#define container_of(ptr, type, member) ({             \
const typeof( ((type *)0)->member ) *__mptr = (ptr);     \
(type *)( (char *)__mptr - offsetof(type,member) );})


typdef struct {
    int x;
    int y;
} Point;

Point p;

int *a = &p.x

assert(&p == container_of(a, Point, x));


typdef struct list_node_s{
    struct list_node_s* next;

typdef struct user_s {
    char *name;
    char *pwd;
    list_node_t node;

user_t u1, u2; = &u2.node;

assert(&u2 == container_of(, user_t, node))

The End