根据结构体成员地址得到结构体入口地址,内核代码

#include <stdio.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)); })

struct student{
char name[20];
char sex;
}stu={"zhangsan",'m'};

int main()
{
struct student *stu_ptr;
size_t offset;

const typeof(((struct student*)0)->sex)* _mptr = &stu.sex;
offset = (size_t)(&((struct student*)0)->sex);
stu_ptr = (struct student*)((char*)_mptr - offset);


//成员的地址,结构体类型,结构体成员名称
stu_ptr = container_of(&stu.sex, struct student,sex);
printf("offsetof stu.sex = %d\n", offset);
printf("stu_ptr->name: %s\t stu_ptr->sex: %c\n", stu_ptr->name ,stu_ptr->sex);

return 0;
}

posted on 2017-12-12 11:09  遥远飞行  阅读(410)  评论(0编辑  收藏  举报

导航