得到结构体中成员的偏移

来源:互联网 发布:软件测试管理工具qc 编辑:程序博客网 时间:2024/04/26 14:19

#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强制转换成指向数据类型的指针,再把它的成员的地址强制转换成数字,就得到了成员在结构体中的偏移量。