已知机构体的定义和成员,怎么计算该成员在此结构体内的偏移量呢?
例如 struct testStruct {
int tmpI;
char tmpS[10];
float tmpF;
};
tmpI的偏移量为0,tmpS的偏移量为4,tmpF成员的偏移量为16,怎样通过简单的程序计算出来。
c:
#define MEMBER_OFFSET(type,member) ((unsigned long)(&((type*)0)->member)))
c++:
testStruct a;
cout <<(char*)&a.tmpI-(char*)a <<endl;
cout <<(char*)a.tmpS-(char*)a <<endl;
cout <<(char*)&a.tmpF-(char*)a <<endl;
C/C++ 中已经提供了宏 offsetof 计算成员的偏移量。注意包含头文件:C 是 <stddef.h>,C++ 是 <cstddef>。