C语言结构体成员偏移量的计算
程序员文章站
2024-03-14 13:28:52
...
请参考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