一、函数原型
(unsigned long)(&((type *)0)->member))
具体解释:offsetof获取结构体的偏移
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
参数:
ptr:指向type的成员
type:结构体类型
member:结构体的成员
1、(type *)((char *)(ptr)
:指向type结构体的成员member,实际应用type.member
2、(unsigned long)(&((type *)0)->member))
:获取offset结构体的偏移
3、函数作用:找出ptr指向的type类型结构体的首地址
二、函数demon
#include<stdio.h>
#include <stdlib.h>
//#include <sys/queue.h>
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
struct student {
int age;
int score;
};
int main()
{
struct student student1;
student1.age=18;
student1.score=95;
struct student *p= list_entry(&(student1.score),struct student,score);
printf("student1.age addr is %lld\n",&student1.age);
printf("p is %d ,addr is %lld \n",p->age,&p->age);
return 0;
}
运行结果: