Accessing the union members using the name of unio

2019-08-06 03:23发布

问题:

How can I access the union members which exist inside the structure?

Consider the code snippet:

struct Emp {

  char name[20];
   union address {

     char addr[50];
   };

};

struct Emp e;

Using e, how do I access the addr type without creating any union object?

回答1:

Unnamed struct/union fields within structs/unions is supported in C11 and also GCC extension. If this feature is on, you can use e.addr directly. Note that the tag name should be empty, either.

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

If it's not supported, you need to give the union a name and use e.u.addr.

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


回答2:

Give the union member a name:

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

Now you can access it like so:

struct Emp e;
e.address.addr;


回答3:

Union should be named first and then access as

[struct_object_name].[union_name].[union_datamember]

Here,

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

struct Emp e;

address it as

e.Emp_address.addr


标签: c struct unions