# cat contof.c
#include <stdio.h>
#include <string.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
typedef struct student
{
int id;
char name[30];
int math;
}Student;
int main()
{
Student stu;
Student *sptr = NULL;
stu.id = 123456;
strcpy(stu.name,"风家三郎");
stu.math = 90;
printf("pstu=%p\n",&stu);
sptr = container_of(&stu.id,Student,id);
printf("sptr=%p\n",sptr);
sptr = container_of(&stu.name,Student,name);
printf("sptr=%p\n",sptr);
sptr = container_of(&stu.math,Student,math);
printf("sptr=%p\n",sptr);
return 0;
}
具体详解,见下面
参考 https://blog.csdn.net/jiuguaqiao6494/article/details/118046667