Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a standard feature in C [duplicate]

I can't understand if this feature is standard or only some weird stuff.

struct A {
    int field_1;
    int field_2;
};

struct B {
    struct A super;
};

int main() {
    struct B b;

    // Normally i must access like that to field_2
    b.super.field_2 = 10;
    
    // Is legal to access in this manner?
    struct A* generic_ref = (struct A*)&b;
    generic_ref->field_2 = 10;

    return 0;
}

I tried on gcc and it seems to work, but i think that can be something that can break in some more complicated situations.

like image 882
Tonaion Avatar asked Feb 02 '26 20:02

Tonaion


2 Answers

This is allowed, as a pointer to a struct can be converted to a pointer to its first member.

This is specifically spelled out in section 6.7.2.1p15 of the C standard:

A pointer to a structure object, suitably converted, points to its initial member

like image 72
dbush Avatar answered Feb 04 '26 08:02

dbush


The C standard guarantees that there is no padding before the first member of a struct6.7.2.1: Structure and union specifiers, paragraph 13):

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.

Emphasis mine.

In other words, if you dereference a pointer to a struct B contains another struct, struct A as its first and/or only member, as if it were a struct A, the resulting struct A would be populated as you would expect...

like image 24
Govind Parmar Avatar answered Feb 04 '26 10:02

Govind Parmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!