6.5.10 偏移量函数库
偏移量函数库提供了计算结构体成员的偏移量函数,包含在头文件stddef.h中,函数声明如下。
int offsetof(structure,member);
该函数计算member从开始位置的偏移量,并返回字节形式的偏移量值。其中,参数structure为结构体,member为结构体成员,程序示例如下。
include<stddef.h>//头文件
include<stdio.h>
struct Mystruct//自定义结构
{
unsigned long num;
unsigned char type;
unsigned int len;
};
typedef struct Mystruct index;//声明index
void main(void)//主函数
{
int x,y;
x=offsetof(index,num);//调用offsetof,计算偏移量
y=offsetof(struct Mystruct,len);//调用offsetof,计算偏移量
printf(“x=%d,y=%d\n”,x,y);//输出结果
}
该程序可以在KeilµVision3编译环境中执行,运行时将输出如下内容。
x
=
0
,
y
=
5
在该程序中,自定义了结构Mystruct,而在main主函数中通过调用offsetof函数来计算结构中成员的偏移量,最后打印输出结果。