#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a;
char b;
int c;
float d;
double e;
char g;
char h;
}test_T;
#define offset(T, f) ((int)(&(((T*)0)->f)))
#define print_f(T, f); printf(#T"->"#f": %d/n", offset(T, f));
int main(int argc, char* argv[])
{
print_f(test_T, a);
print_f(test_T, b);
print_f(test_T, c);
print_f(test_T, d);
print_f(test_T, e);
print_f(test_T, g);
print_f(test_T, h);
return 0;
}
#define offset(T, f) ((int)(&(((T*)0)->f)))原理:
把0强制转换成指向数据类型的指针,再把它的成员的地址强制转换成数字,就得到了成员在结构体中的偏移量。