关于网友提出的“ 宏偏移量问题”问题疑问,本网通过在网上对“ 宏偏移量问题”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: 宏偏移量问题
描述:宏
1. /**
2. * container_of - 通过结构体的一个成员获取容器结构体的指针
3. * @ptr: 指向成员的指针。
4. * @type: 成员所嵌入的容器结构体类型。
5. * @member: 结构体中的成员名。
6. *
7. */
8. #define container_of(ptr, type, member) ({ \
9. const typeof( ((type *)0)->member ) *__mptr = (ptr); \
10. (type *)( (char *)__mptr - offsetof(type,member) );})
在这个宏中, 这个地方(char *)__mptr - offsetof(type,member) )
为什么要把__mptr 先转换为char*类型在进行计算偏移
解决方案1: C/C++在对指针进行加减时会自动将偏移量乘上指针指向的数据类型的大小,比如定义一个int *p;那么,p+i的地址实际上为
p+i*sizeof(int);而如果将p转换成char*,(char*)p+i的地址为(char*)p+i*sizeof(char), sizeof(char)为1, 所以结果为 (char*)p+i.
这里offsetof的结果为实际的偏移量,不应该再去乘上类型大小,所以就通过将__mptr转换为char*来实现这一目的.
解决方案2: 指针的偏移量是按照对象个数计算的。
When an expression that has integral type is added to or subtracted
from a pointer, the integral value is first multiplied by the size of
the object pointed to.
这里是需要按字节计算的,所以转换为char *
解决方案3: char*保证是以单字节计算偏移量的,因指针如果直接进行减法运算,是和类型相关的
以上介绍了“ 宏偏移量问题”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/2554890.html