#include "stdafx.h"
#include <iostream>
struct testStruct{
char a;
short b;
int c;
char path[1024];
int d;
};
#define PARAM_OFFSET(Strct, Field) ((unsigned long)(unsigned long*)&(((Strct *)0)->Field))
int main(int argc, char* argv[])
{
printf("a's offset:%d, b's offset:%d,c's offset:%d,path's offset:%d,c's d:%d/n",
PARAM_OFFSET(testStruct,a),
PARAM_OFFSET(testStruct,b),
PARAM_OFFSET(testStruct,c),
PARAM_OFFSET(testStruct,path),
PARAM_OFFSET(testStruct,d));
printf("size is : %d",sizeof(testStruct));
testStruct* testStru = new testStruct();
testStru->a = 2;
testStru->c = 4;
int offset = PARAM_OFFSET(testStruct,c);
short value = 5;
*((unsigned char*)testStru + offset) = value;
++testStru;
return 0;
}
宏PARAM_OFFSET(Strct, Field) 先把0地址转换为结构体(即结构体的首地址为0),那么结构体成员变量的地址即为其偏移量。通过结构体的指针偏移量来快速方便地获取或修改结构体成员变量的值。