container_ofマクロ
[root@localhost c]# cat a.c
#include <stdio.h> #include <stddef.h> #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) struct babakaka { int a; int b; int c; int d; int e; }; void main() { struct babakaka aaa; int *member[5]; member[0] = &aaa.a; member[1] = &aaa.b; member[2] = &aaa.c; member[3] = &aaa.d; member[4] = &aaa.e; printf("-:%x\n", &aaa); printf("a:%x\n", container_of(member[0], struct babakaka, a)); printf("b:%x\n", container_of(member[1], struct babakaka, b)); printf("c:%x\n", container_of(member[2], struct babakaka, c)); printf("d:%x\n", container_of(member[3], struct babakaka, d)); printf("e:%x\n", container_of(member[4], struct babakaka, e)); }
[root@localhost c]# ./a.out -:bf9aeb78 a:bf9aeb78 b:bf9aeb78 c:bf9aeb78 d:bf9aeb78 e:bf9aeb78