计算C结构体成员偏移量两种方式本质上是一样的
#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\t:%ld \t2:%ld\n",offsetof(test_t, a),OFFSET(test_t, a)); printf("b:offset\t:%ld \t2:%ld\n",offsetof(test_t, b),OFFSET(test_t, b)); printf("p:offset\t:%ld \t2:%ld\n",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中实现方式与这个宏一致。
Go as far as your heart will take you.