C 结构的第一个字段是否总是保证偏移量为 0? [英] Is the first field of a C structure always guaranteed to be at offsetof 0?

查看:14
本文介绍了C 结构的第一个字段是否总是保证偏移量为 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 C 编程语言...

Regarding the C programming language...

C/C++ 结构偏移 中的部分问题指出& 并不总是指向在结构的第一个字段的第一个字节处"

Part of the question at C/C++ Structure offset states that "& does not always point at the first byte of the first field of the structure"

但是在 http://www.lysator 上查看ANSI 基本原理".liu.se/c/rat/c5.html 它在第 3.5.2.1 节结构和联合说明符中指出一开始不能出现空洞".所以我不确定基本原理"是否是明确的,但它似乎与那个非常明显的问题的那部分矛盾.

But looking over the "ANSI Rationale" at http://www.lysator.liu.se/c/rat/c5.html it states "no hole may occur at the beginning" in section 3.5.2.1 Structure and union specifiers. So I'm not sure if the "Rationale" is definitive but it does seem to contradict that part of that highly visible question.

那么,它是什么?C 结构的第一个字段是否总是保证偏移量为 0?

struct A
{
    int x;
};

struct B
{
    struct A myA;
    int y;
};

B myB;

&myB 是否保证&(myB.myA) 以可移植的方式相同?

Is &myB guaranteed to be the same as &(myB.myA) in a portable way?

(更具体地说,Libev 中的 libev 用户数据技巧,如何将参数传递给相关回调 和许多其他地方确实假设结构中的第一个字段在 offsetof 0 处......真的可以移植吗?)

(More concretely, the libev user-data trick at Libev, How to pass arguments to relevant callbacks and many other places does assume that the first field in the structure is at offsetof 0... is that really portable?)

推荐答案

来自 C99 标准第 6.7.2.1 节第 13 条:

From the C99 standard section 6.7.2.1 bullet point 13:

在结构对象中,非位域成员和位域所在的单元驻留的地址按其声明的顺序增加.一个指向 a适当转换的结构对象指向其初始成员(或者如果该成员是位域,然后到它所在的单元),反之亦然.可能有无名在结构对象内填充,但不在其开头.

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

因此,您的问题的答案是肯定的.

The answer to your question is therefore yes.

这篇关于C 结构的第一个字段是否总是保证偏移量为 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆