#include <stdio.h> #include <stddef.h> typedef struct test_st { char a[3]; char b[13]; int *p; }test_t; #define OFFSET(type,member) ((size_t)(&(((type *)0)->member))) int main() { printf("a:offset :%ld 2:%ld ",offsetof(test_t, a),OFFSET(test_t, a)); printf("b:offset :%ld 2:%ld ",offsetof(test_t, b),OFFSET(test_t, b)); printf("p:offset :%ld 2:%ld ",offsetof(test_t, p),OFFSET(test_t, p)); return 0; }
结果:
a:offset :0 2:0 b:offset :3 2:3 p:offset :16 2:16
offsetof函数在linux中实现方式与这个宏一致。