Aliasing array with pointer-to-struct without violating the standard

大城市里の小女人 提交于 2019-12-04 04:16:11

According to ISO/IEC9899/TC2 section 6.7.2.1, paragraph 13:

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

So as long as you are casting the struct pointer to the pointer type of the first member it should not violate strict aliasing (specified in section 6.5 paragraph 7) an element may also be accessed via

an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union)

but this only works in the other direction (accessing a member via a struct pointer, not accessing a struct via a member pointer)

None of your examples break the rules, even the cast of a char array to a struct pointer.
All you need to care about is:

  • Array is big enough
  • member alignment
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!