C: How to access different types of anonymous or unnamed nested structs -


i noticed there few ways define structs inside other structs in c:

struct s {     int abc;      struct {         int a;     };      struct {         int b;     } intern;      struct {         int c;     };      struct i2 {         int d;     } intern2;      struct i3 {         int e;     };     struct i3 intern3; }; 

this struct compiles fine using gcc or g++, assume parameters accessible in way. tried this:

int main(int argc, char const *argv[]) {     struct s mystruct;      mystruct.abc = 0;     mystruct.a = 1;     mystruct.intern.b = 2;     mystruct.c = 3; // <-- not compile     mystruct.intern2.d = 4;     mystruct.intern3.e = 5;      return 0; } 

apart access mystruct.c, compiles (compile error message ‘struct s’ has no member named ‘c’). accessing struct parameters in correct way? there alternatives? how access c parameter?

in code,

struct {         int c;     }; 

there no member variable of type struct i neither qualifies anonymous structure note. if create variable of type, you'll able access member variable c, similar you've done struct i3 intern3 variable.

adding bit regarding error message you're seeing,

struct s has no member named c

because, in case of anonymous structure, members considered direct member of containing structure. in case of struct definition tag, structure not anonymous structure , member of structure needs structure variable of type accessed.


note:

regarding anonymous structure, quoting c11, chapter §6.7.2.1, (emphasis mine)

an unnamed member type specifier structure specifier no tag called anonymous structure; unnamed member type specifier union specifier no tag called anonymous union. members of anonymous structure or union considered members of containing structure or union. applies recursively if containing structure or union anonymous.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -