offsetof(type, member-designator)
优质
小牛编辑
143浏览
2023-12-01
描述 (Description)
C库宏offsetof(type, member-designator)产生一个size_t类型的常量整数,它是结构成员从结构开始的字节偏移量。 该成员由成员 - 指定者给出,结构的名称以类型给出。
声明 (Declaration)
以下是offsetof()宏的声明。
offsetof(type, member-designator)
参数 (Parameters)
type - 这是其中member-designator是有效成员指示符的类类型。
member-designator - 这是类类型的成员指示符。
返回值 (Return Value)
此宏返回size_t类型的值, size_t是类型中成员的偏移值。
例子 (Example)
以下示例显示了offsetof()宏的用法。
#include <stddef.h>
#include <stdio.h>
struct address {
char name[50];
char street[50];
int phone;
};
int main () {
printf("name offset = %d byte in address structure.\n",
offsetof(struct address, name));
printf("street offset = %d byte in address structure.\n",
offsetof(struct address, street));
printf("phone offset = %d byte in address structure.\n",
offsetof(struct address, phone));
return(0);
}
让我们编译并运行上面的程序,这将产生以下结果 -
name offset = 0 byte in address structure.
street offset = 50 byte in address structure.
phone offset = 100 byte in address structure.