Does the complexity of the C structure make this use unsafe?

Suppose I have a structure, be it union'd or otherwise:

    typedef struct {
        union {
            struct { float x, y, z; } xyz;
            struct { float r, g, b; } rgb;
            float xyz[3];
        } notAnonymous;
    } Vector3;

I heard that some compilers automatically compose structures to improve performance by creating word-aligned borders.

Presumably, this synergy means that the size of the structure cannot be guaranteed by the sum of the sizes of its components, and therefore, there is a change in data distortion and / or overflow for the array xyzsin the following:

inline Vector3 v3Make(float x, float y, float z) { Vector3 v = {x,y,z}; return v; }
float xyzs[6];
*(Vector3*)&xyzs[3] = v3Make(4.0f,5.0f,6.0f);
*(Vector3*)&xyzs[0] = v3Make(1.0f,2.0f,3.0f);

Correctly?

+5
source share
4 answers

, , - . #pragma pack __attribute__((packed)), . 32- , , , . sizeof , .

, Vector3 float . . , :

*(Vector3 *)&xyzs[3] = v3Make(4.0f, 5.0f, 6.0f);

, . xyzs Vector3, float.

+3

, / .

... , , , . .

0

C , , ( ) , , undefined (- ?), , . ( ), , , .

With that said in my book, at least this kind of hacking is a gratuitous call to undefined behavior for strong syntax vinegar and is unacceptable. If you ever need access to data in the style of an array, just use the shape of the array. It is much less difficult to remember that vector components are always v[0], v[1]and v[2]than to remember that v[1]they rgb.gcan refer to the same object in memory ...

0
source

All Articles