#include <stdio.h>
#ifdef offsetof
#undef offsetof
#endif
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#ifdef container_of
#undef container_of
#endif
#define container_of(ptr, type, member) ({\
const typeof( ((type *)0)->member ) *__mptr = (ptr);\
(type *)( (char *)__mptr - offsetof(type,member) );})
struct test_struct {
int num;
char ch;
float f1;
};
struct test_struct_array {
char ch;
char ch_1;
int num;
char ch_2;
float f1;
struct test_struct sa[3];
};
struct test_struct_pointer {
int num;
struct test_struct *sp;
};
int main(void)
{
struct test_struct *test_struct_1;
struct test_struct init_struct ={12,'a',12.3};
char *ptr_ch_1 = &init_struct.ch;
test_struct_1 = container_of(ptr_ch_1,struct test_struct,ch);
printf("test_struct_1 =%p &init_struct = %p\n",test_struct_1,&init_struct);
printf("test_struct_1->ch =%c\n",test_struct_1->ch);
struct test_struct_array *test_struct_a_1;
struct test_struct *sa = NULL;
struct test_struct_array test_struct_a_test = {'a','b',6,'c',1.22
,12,'e',12.3
,3,'f',3.3
,8,'g',8.3
};
sa = &test_struct_a_test.sa[1];
test_struct_a_1 = container_of(sa,struct test_struct_array,sa[1]);
printf("test_struct_a_1 =%p &test_struct_a_test = %p\n",test_struct_a_1,&test_struct_a_test);
printf("test_struct_a_1->ch_1 =%c test_struct_a_1.sa[1].ch=%c\n",test_struct_a_1->ch_1,test_struct_a_1->sa[1].ch);
struct test_struct *st = &init_struct;
struct test_struct_pointer test_struct_p = {4,st};
struct test_struct_pointer *test_s_p = container_of(&test_struct_p.sp, struct test_struct_pointer, sp);
printf("test_s_p = %p test_s_p->num = %d &test_struct_pointer = %p\n",test_s_p,test_s_p->num,&test_struct_p);
return 0;
}
测试结果
$ ./test.exe
test_struct_1 =0xffffcbcc &init_struct = 0xffffcbcc
test_struct_1->ch =a
test_struct_a_1 =0xffffcb90 &test_struct_a_test = 0xffffcb90
test_struct_a_1->ch_1 =b test_struct_a_1.sa[1].ch=f
test_s_p = 0xffffcb80 test_s_p->num = 4 &test_struct_pointer = 0xffffcb80
正常来说我们使用container_of 的情况都是通过一个结构体成员指针然后获取其所在的结构体的指针,但是有的时候内部是一个数组,通过不同的数组指针获取到其所在的结构体指针(container_of只能是其成员,而不能说成员的成员)