首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

container_of解释,该怎么解决

2012-05-13 
container_of解释#ifndef offsetof#defineoffsetof(type, field)((long)&(((type *)0)-field))#endif#ifn

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*才是计算多少字节的偏移。

热点排行