Accessing the union members using the name of unio

2019-08-06 03:33发布

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?

标签: c struct unions
3条回答
家丑人穷心不美
2楼-- · 2019-08-06 03:58

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;
};
查看更多
smile是对你的礼貌
3楼-- · 2019-08-06 04:00

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
查看更多
做个烂人
4楼-- · 2019-08-06 04:23

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;
查看更多
登录 后发表回答