Can I treat a struct like an array?

前端 未结 8 1511
野趣味
野趣味 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 19:02

    Whoa. There are a lot of answers saying it will work. It is not guaranteed by the C standard. In response to a comment asking for a real-world example, there is this excellent post by Chris Torek from comp.lang.c. The final quote is: The lesson here is the same as always: "If you lie to the compiler, it will get its revenge."

    Definitely a must read for those who think it's OK to treat a struct of homogeneous members as an array.

    0 讨论(0)
  • 2020-12-03 19:04

    No, it is not legal. And almost any time you find yourself using a cast, you should suspect there is something deeply wrong with your code. I suspect that someone will shortly suggest using a union, but that will not be legal either.

    Of course, legal or not, either the approach you suggest in your question or the use of a union will probably "work" - but that is not what you asked.

    0 讨论(0)
提交回复
热议问题