結構體偏移量

#include <stdio.h>
#include <stdlib.h>

#pragma pack(2)

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;
}

輸出結果:

test_T->a: 0
test_T->b: 4
test_T->c: 6
test_T->d: 10
test_T->e: 14
test_T->g: 22
test_T->h: 23

 


測試環境:

Linux version 2.6.23.1-42.fc8 ([email protected]) (gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)) #1 SMP Tue Oct 30 13:55:12 EDT 2007


&(((type*)0)->field)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章