Can I treat a struct like an array?

前端 未结 8 1645
野趣味
野趣味 2020-12-03 18:11

I have a struct for holding a 4D vector

struct {
    float x;
    float y;
    float z;
    float w;
} vector4f

And I\'m using a library th

8条回答
  •  醉话见心
    2020-12-03 18:52

    You can write code that would make an attempt to treat it as an array, but the language makes no guarantees about the functionality of that code. The behavior is undefined.

    In C language taking a storage region occupied by a value of one type and reinterpreting it as another type is almost always illegal. There are a few exceptions from that rule (which is why I said "almost"), like you can reinterpret any object as a char array, but in general it is explicitly illegal.

    Moreover, the possible dangers are not purely theoretical, and it is not just about the possible alignment differences between arrays and structs. Modern compilers might (and do) rely on the aforementioned language rule in order to perform aliasing optimizations (read about strict aliasing semantics in GCC, for one example). In short, the compler is allowed to translate code under the assumption that memory occupied by a struct can never overlap memory occupied by an array of float. This often leads to unexpected results when people start using tricks like in your post.

提交回复
热议问题