container_of解释
#ifndef offsetof
#define offsetof(type, field) ((long)&(((type *)0)->field))
#endif
#ifndef container_of
#define container_of(ptr, type, member) ({ \
const typeof(((type*)0)->member) *__mptr = (ptr); \
(type*)((char*)__mptr - offsetof(type, member)); \
})
#endif
上述红色字体部分(char*)__mptr是为何?为什么要强制转换类型为char*,本来的类型是typeof(((type*)0)->member)的?
[解决办法]
(type*)((char*)__mptr - offsetof(type, member));
如果不用(char*)强转,那么这个 - 操作意义就不同了。返回的地址也就不同了。
char *p = (char*)&n;
p-1;
int *pp = (int*)&n;
pp-1;
p-1与pp-1 是不同样的。
[解决办法]
指针相减得到的是元素个数,所以指针类型转成char*才是计算多少字节的偏移。