C: How to access various types of anonymous or unnamed nested structures

I noticed that there are several ways to define structures inside other structures in C:

struct s {
    int abc;

    struct {
        int a;
    };

    struct {
        int b;
    } intern;

    struct i {
        int c;
    };

    struct i2 {
        int d;
    } intern2;

    struct i3 {
        int e;
    };
    struct i3 intern3;
};

This structure compiles using gcc or g ++, so I assume that all options are available in some way. I tried this as follows:

int main(int argc, char const *argv[])
{
    struct s mystruct;

    mystruct.abc = 0;
    mystruct.a = 1;
    mystruct.intern.b = 2;
    mystruct.c = 3; // <-- does not compile
    mystruct.intern2.d = 4;
    mystruct.intern3.e = 5;

    return 0;
}

Besides access mystruct.c, everything compiles (compilation error message β€˜struct s’ has no member named β€˜c’). Am I referring to structural parameters correctly? Are there any alternatives? How to access the parameter c?

+4
source share
4 answers

In your code

struct i {
        int c;
    };

- struct i, . , - c, , struct i3 intern3.

, ,

struct s c

. struct , .


:

, C11, Β§6.7.2.1, ( )

, , ; , no tag . . , .

+2

gcc docs:

ISO C11 , GCC , , , . :

 struct {
   int a;
   union {
     int b;
     float c;
   };
   int d;
 } foo;

'foo.b.

mystruct.a, . mystruct.c, c i.

:

 struct i {
        int c;
    };

to

struct {
    int c;
}

mystruct.c.

+2

c strut i. struct i.

, c.

mystruct.c, , c s, .

0

,

That is what the unnamed says - he has no name, so you cannot access him by name.

The only reason to have unnamed elements in the structure is if you mirror the structure provided from the outside, and you do not need its separate parts, so you will only name the parts that you want to receive.

0
source

Source: https://habr.com/ru/post/1648369/


All Articles