Can I treat a struct like an array?

前端 未结 8 1644
野趣味
野趣味 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:41

    Let's just throw all arguments about the Right Way™ to do something out the window for a minute.

    Does it work to treat that struct as an array? Yes. Will it work in all cases, across all compilers and platforms? No.

    Floats tend to be 32-bit, and even on my 64-bit machine, they get aligned on 32-bit word boundaries.

    #include 
    
    struct {
            float x;
            float y;
            float z;
            float w;
    } vector4f;
    
    float array4f[4];
    
    int main(int argc, char **argv) {
            printf("Struct: %lu\n", sizeof(vector4f)); // 16
            printf(" Array: %lu\n", sizeof(array4f));  // 16
    
            return (0);
    }
    

提交回复
热议问题