C 标准对结构体指针及其第一个成员有何规定?

发布于 2024-09-05 06:35:53 字数 364 浏览 2 评论 0原文

考虑以下两个 struct

struct a
{
    int a;
};

struct b
{
    struct a a_struct;
    int b;
};

以下 struct b 实例化:

struct b b_struct;

以及此条件:

if (&b_struct == (struct b*)&b_struct.a_struct)
    printf("Yes\n");

C 标准是否要求此值始终为 true?

Consider the following two struct:

struct a
{
    int a;
};

struct b
{
    struct a a_struct;
    int b;
};

the following instantiation of struct b:

struct b b_struct;

and this condition:

if (&b_struct == (struct b*)&b_struct.a_struct)
    printf("Yes\n");

Does the C standard mandate this to always evaluate true?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

踏月而来 2024-09-12 06:35:53

是的,根据 6.7.2.1,“在结构体对象中,非位域成员和位域所在的单元的地址按照它们声明的顺序递增。指向结构体对象的指针,适当转换后,指向其初始成员(或者如果该成员是位字段,则指向它所在的单元),反之亦然。在结构对象中可能有未命名的填充,但在其开头则不然。”

Yes, according to 6.7.2.1, "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."

三生路 2024-09-12 06:35:53

在 C 标准中找不到它,但答案是“是” - C++ 标准说:

指向 POD 结构对象的指针,
使用适当转换
reinterpret_cast,指向它的
初始成员(或者如果该成员是
位域,然后到其中的单位
它驻留),反之亦然。 [笔记:
因此可能存在未命名的
POD 结构对象内的填充,
但不是在开始时,必要时
以实现适当的对齐。 ]

由于 C 和 C++ POD 对象必须兼容,因此 C 也必须如此。

Can't find it in the C Standard, but the answer is "yes" - the C++ Standard says:

A pointer to a POD-struct object,
suitably converted using a
reinterpret_cast, points to its
initial member (or if that member is a
bit-field, then to the unit in which
it resides) and vice versa. [Note:
There might therefore be unnamed
padding within a POD-struct object,
but not at its beginning, as necessary
to achieve appropriate alignment. ]

As C and C++ POD objects must be compatible, the same must be true for C.

甜妞爱困 2024-09-12 06:35:53

是的。

第一个成员前面不得有任何填充。

如果使用适当的强制转换,结构的地址与其第一个成员的地址相同。

资源

Yes.

There must not be any padding in front of the first member.

The address of a structure is the same as the address of its first member, provided that the appropriate cast is used.

resource

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文