Access to union members using association name

How can I access members of an association that exist within a structure?

Consider a piece of code:

struct Emp {

  char name[20];
   union address {

     char addr[50];
   };

};

struct Emp e;

Using e, how do I access a type addrwithout creating any union object?

0
source share
3 answers

The concepts of struct / union in structures / unions are supported in C11, as well as in the GCC extension. If this feature is enabled, you can use it directly e.addr. Please note that the tag name must be empty.

struct Emp {
    char name[20];
    union {
        char addr[50];
    };
};

If it is not supported, you need to specify a name unionand use e.u.addr.

struct Emp {
    char name[20];
    union address {
        char addr[50];
    } u;
};
+3
source

:

struct Emp {
   char name[20];
   union {
     char addr[50];
   } address;
};

:

struct Emp e;
e.address.addr;
0

,

[struct_object_name].[union_name].[union_datamember]

struct Emp {
   char name[20];
   union {
     char addr[50];
   } Emp_address;
};

struct Emp e;

e.Emp_address.addr
0

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


All Articles