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

查看:82
本文介绍了是否始终保证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上的"ANSI基本原理". lysator.liu.se/c/rat/c5.html 指出,第3.5.2.1节结构和联合说明符"中的开始时不得出现孔".因此,我不确定"Rationale"是否是确定的,但它确实与该高度可见的问题的这一部分相矛盾.

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)相同?

(更具体地说,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:

在结构对象中,非位域成员和其中位域的单位 居住的地址按照声明的顺序增加.指向一个的指针 经过适当转换的结构对象指向其初始成员(或者该成员是 位域,然后到它所在的单元),反之亦然.可能有未命名 在结构对象中填充,而不是在其开头填充.

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天全站免登陆