计算结构体中成员变量的偏移
被人问到这个问题,各种解决。
google一下,MFC中有一个OFFSET宏,就有这个功能。
写一下:
#define offsetof(structure, member) ((int)(&((structure *)0)->member))
eg:
#include <iostream>
using namespace std;
#include <stdio.h>
#define offsetof(structure, member) ((int)(&((structure *)0)->member))
struct test_struct
{
int a;
char b;
int aa[10];
char bb[2];
};
int main()
{
cout<<offsetof(struct test_struct, a)<<endl;
cout<<offsetof(struct test_struct, b)<<endl;
cout<<offsetof(struct test_struct, aa)<<endl;
cout<<offsetof(struct test_struct, bb)<<endl;
return 0;
}
浙公网安备 33010602011771号