C 标准对结构体指针及其第一个成员有何规定?
考虑以下两个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,根据 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."
在 C 标准中找不到它,但答案是“是” - C++ 标准说:
由于 C 和 C++ POD 对象必须兼容,因此 C 也必须如此。
Can't find it in the C Standard, but the answer is "yes" - the C++ Standard says:
As C and C++ POD objects must be compatible, the same must be true for C.
是的。
第一个成员前面不得有任何填充。
如果使用适当的强制转换,结构的地址与其第一个成员的地址相同。
资源
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