#include <stdio.h> #include <stdlib.h> /* 计算成员变量首部相对于结构变量首部的偏移量 */ #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) /** * 通过结构体中成员变量的首地址找到这个结构体变量的首地址 * @ptr: 成员变量的首地址 * @type: 结构体类型 * @member: 成员变量的名字 */ #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) typedef struct Person { char name[20]; int hight; int weight; } Person; int main() { Person test = {"tongyishu", 170, 60}; Person* _test = container_of(&(test.hight), Person, hight); printf("age : %d\n", _test->weight); //结果为 60 return 0; }
container_of机制
猜你喜欢
转载自www.cnblogs.com/tongyishu/p/11701419.html
今日推荐
周排行