Struct Offset des ersten Elements



  • Hallo,
    ist vom C-Standard garantiert, dass das erste Element (/Member/Attribut ?) eines Structs den Offset 0 hat?

    An einem Beispiel:

    typedef struct
    {
        int x;
        float y;
    } foo;
    
    foo variable;
    variable.x = 42;
    printf("%d", *((int*)(&variable))); // kommt hier immer 42?
    

    Ich weiß zwar von dem Macro offsetof, aber ich brauche eben nur den Offset des ersten Elements, und wenn ich wüsste, dass der immer konstant ist, würde das alles einfacher machen.


  • Mod

    Ja.

    C11, 6.7.2.1 (15) schrieb:

    Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. 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. There may be unnamed padding within a structure object, but not at its beginning.

    P.S.: Ebenso oder mindestens ähnlich ist es schon immer formuliert, ich habe bloß keine Lust, alle alten Standards zu durchwühlen.



  • Ok, danke sehr 🙂


Anmelden zum Antworten