OFFSETOF - Linux手册页

Linux程序员手册 第3部分
更新日期: 2020-06-09

示例

在Linux / i386系统上,使用默认的gcc(1)选项进行编译时,以下程序将产生以下输出:

$ ./a.out
offsets: i=0; c=4; d=8 a=16
sizeof(struct s)=16

Program source

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    struct s {
        int i;
        char c;
        double d;
        char a[];
    };

    /* Output is compiler dependent */

    printf("offsets: i=%zd; c=%zd; d=%zd a=%zd\n",
            offsetof(struct s, i), offsetof(struct s, c),
            offsetof(struct s, d), offsetof(struct s, a));
    printf("sizeof(struct s)=%zd\n", sizeof(struct s));

    exit(EXIT_SUCCESS);
}

遵循规范

POSIX.1-2001,POSIX.1-2008,C89,C99。

出版信息

这个页面是Linux手册页项目5.08版的一部分。有关项目的说明、有关报告错误的信息以及此页面的最新版本,请访问https://www.kernel.org/doc/man-pages/

说明

offsetof()返回字段成员从结构类型开始的偏移量。

该宏非常有用,因为构成结构的字段的大小在不同的实现中可能会有所不同,并且编译器可能会在字段之间插入不同数量的填充字节。因此,元素的偏移量不一定由先前元素的大小之和给出。

如果成员未与字节边界对齐(即,它是位字段),将导致编译器错误。

返回值

offsetof()以字节为单位返回给定类型内给定成员的偏移量。

语法

#include <stddef.h>

size_t offsetof(type, member);

名称

offsetof-结构成员的偏移量

日期:2019-08-20 18:00:57 来源:oir作者:oir