×

offsetof

offsetof(#define offsetof(TYOE,MEMBER) ((int)&((TYPE *)0)->MEMEBER)这个该怎么理解啊)

admin admin 发表于2023-07-20 07:13:55 浏览43 评论0

抢沙发发表评论

本文目录

#define offsetof(TYOE,MEMBER) ((int)&((TYPE *)0)->MEMEBER)这个该怎么理解啊

这个表达式分两部分看,首先确定运算符的优先级,在上面的表达式中,-》最高,&取地址次之,(类型)类型转换最低,故可以这么看:1.(int)&(...),表示将右边括号内的先取地址,然后将地址的值强制转换为int型;2.要引用常数地址0的变量,在C语言中是不允许的,必须进行类型转换,故((TYPE *)0)是将地址0强制转换为TYPE结构提类型的指针,((TYPE *)0)-》MEMEBER则就是引用地址0处的TYPE结构提体的变量MEMEBER,3.结合第1和第2点,慢慢理解,希望对你有用

offsetof函数什么意思啊

offsetof宏的简介定义  在stddef.h头文件中,该宏的完整说明如下:  #ifdef __cplusplus  #ifdef _WIN64  #define offsetof(s,m) (size_t)( (ptrdiff_t)&reinterpret_cast《const volatile char&》((((s *)0)-》m)) )  #else  #define offsetof(s,m) (size_t)&reinterpret_cast《const volatile char&》((((s *)0)-》m))  #endif  #else  #ifdef _WIN64  #define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)-》m) )  #else  #define offsetof(s,m) (size_t)&(((s *)0)-》m)  #endif  #endif /* __cplusplus */功能  该宏用于求结构体中一个成员在该结构体中的偏移量。  在msdn上,该宏被写作:  size_t offsetof( structName, memberName );  第一个参数是结构体的名字,第二个参数是结构体成员的名字。该宏返回结构体structName中成员memberName的偏移量。偏移量是size_t类型的。本段程序示例  #include 《stdio.h》  #include 《stddef.h》  typedef struct  {  int iVal;  int iVal2;  }Test;  typedef struct  {  char ch;  int iNum;  }Test2;  int main(void)  {  Test t = {1, 2};  Test2 t2 = {’t’, 100};  printf(“\naddress of t : %p\naddress of t.iVal : %p\naddress of t.iVal2: %p\n\n“, &t, &(t.iVal), &(t.iVal2));  printf(“offset of iVal in t: %p\n“, offsetof(Test, iVal));  printf(“offset of iVal2 in t: %p\n“, offsetof(Test, iVal2));  printf(“\naddress of t2 : %p\naddress of t2.ch : %p\naddress of t2.iNum: %p\n\n“, &t, &(t2.ch), &(t2.iNum));  printf(“offset of ch in t2: %p\n“, offsetof(Test2, ch));  printf(“offset of iNum in t2: %p\n“, offsetof(Test2, iNum));  return 0;  }  在VS2005中输出:  address of t : 0012FF10  address of t.iVal : 0012FF10  address of t.iVal2: 0012FF14  offset of iVal in t: 00000000  offset of iVal2 in t: 00000004  address of t2 : 0012FF10  address of t2.ch : 0012FF00  address of t2.iNum: 0012FF04  offset of ch in t2: 00000000  offset of iNum in t2: 00000004  需要注意的是,Test2中iNum成员的偏移量

#define offsetof(s,m) (size_t)&(((s*)0)->m) 请高手详解上述宏定义的所作的工作

这里定义的是,一个宏,用宏来实现函数的功能。如果你在下面调用了offsetof(2,4);他就等于(size_t)&(((2*)0)-》4) ;宏定义的这样方式,编译阶段不对函数的参数进行检查,所以这样是一种很不好的用法,