- 论坛徽章:
- 0
|
- #include <stdio.h>
- #define FIND(TYPE,MEMBER) (size_t)&(((TYPE*)0)->MEMBER)
- #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 list_head {
- struct list_head *next, *prev;
- };
- struct student
- {
- int a;
- char b[19];
- double c;
- struct list_head list;
- };
- int main(void)
- {
- struct student s= {1,{0},0.0,{NULL,NULL}};
- struct list_head * ptr = &s.list;
- printf("%08x\n",s);
- printf("%08x\n",&s);
- printf("%08x\n",&s.a);
- printf("%08x\n",&s.b);
- printf("%08x\n",&s.c);
- printf("%08x\n",FIND(struct student,c));
- struct student *stu = container_of(ptr,struct student, list);//这一句上有问题。
- printf("%08x\n",stu->a);
- return 0;
- }
复制代码 你忘记声明 container_of 中的 offsetof 宏了.
而且在使用 container_of 的时候, 也有错误. 第三个参数, 是对象在结构体中的名称. |
|