offsetof,程序语言,该宏用于求结构体中一个成员在该结构体中的偏移量。
size_t offsetof( structName, memberName );
第一个参数是结构体的名字,第二个参数是结构体成员的名字。该宏返回结构体structName中成员memberName的偏移量。偏移量是size_t类型的。
例程:
#include <stddef.h>
#include <stdio.h>
struct address {
char name[50];
char street[50];
int phone;
};
int main()
{
printf(“address 结构中的 name 偏移 = %d 字节。\n”,
offsetof(struct address, name));
printf(“address 结构中的 street 偏移 = %d 字节。\n”,
offsetof(struct address, street));
printf(“address 结构中的 phone 偏移 = %d 字节。\n”,
offsetof(struct address, phone));
return(0);
}
运行结果:
address 结构中的 name 偏移 = 0 字节。
address 结构中的 street 偏移 = 50 字节。
address 结构中的 phone 偏移 = 100 字节。