简体   繁体   English

我可以安全地将第一个结构成员的地址解释为整个结构的地址吗?

[英]Can I safely interpret the first struct member's address as that of the whole struct?

I'm implementing my own list similar to one from Linux list.h , but don't want to bother with container_of thing. 我正在实现自己的类似于Linux list.h中的列表的列表,但不想打扰container_of的东西。

I've read that C compiler is not allowed to reorder struct members, but is there a guarantee that the first member's offset is always zero? 我读过C编译器不允许对结构成员进行重新排序,但是是否可以保证第一个成员的偏移量始终为零?

Can I just impose a restriction that list head member must be declared first to be able to get the whole struct member simply by casting head address to the container type? 我是否可以强加一个限制,即必须首先声明列表头成员才能通过将头地址强制转换为容器类型来获取整个struct成员?

From C standard C标准

6.7.2.1 Structure and union specifiers 6.7.2.1结构和联合说明符

15 . 15。 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. 结构对象内可能存在未命名的填充,但在其开始处没有。

Emphasis mine 重点矿

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM