#include <stdio.h>
#include <stddef.h>
#define to_struct(ptr, type, member) ({ \
const typeof( ((type*)0)->member ) *__mptr = (ptr); \
(type *)( (char*)__mptr - offsetof(type, member) );})
struct student {
int a;
char b;
int math;
};
int
main(int argc, char **argv)
{
struct student stu = {
.a = 13,
.b = 'b',
.math = 100,
};
struct student *ptr;
int *p;
p = &stu.math;
printf("p is : %d\n", *p);
ptr = to_struct(p, struct student, math);
printf("ptr.b is : %c\n", ptr->b);
return 0;
}
~
应用层的container_of()实现
最新推荐文章于 2023-11-26 16:27:51 发布