天天看點

C語言結構體成員偏移量的計算

請參考https://blog.csdn.net/coding__madman/article/details/51556411

計算方式:

1. 使用宏函數:

#include <stddef.h>
 
       size_t offsetof(type, member);
           

2. 自己計算偏移(B-A形式)

測試代碼如下:

#include <stdio.h>
#include <stddef.h>

struct str
{
        int a;
        int b;
};
int main()
{
        printf("a = %d\n",offsetof(struct str,a));
        printf("b = %d\n",offsetof(struct str,b));
        struct str s;
        printf("a = %d\n",(int)(&(s.a))-(int)(&s));
        printf("b = %d\n",(int)(&(s.b))-(int)(&s));

        printf("b = %d\n",(int)&(((struct str*)0)->b));
        return 0;
}
           

運作結果: 

[[email protected] tmp]# ./a.out 
a = 0
b = 4
a = 0
b = 4
b = 4
           

繼續閱讀