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

运行结果: 

[root@localhost tmp]# ./a.out 
a = 0
b = 4
a = 0
b = 4
b = 4

猜你喜欢

转载自blog.csdn.net/u011285208/article/details/89211404
今日推荐