Structure and tagged union in c

独自空忆成欢 提交于 2020-01-06 15:32:09

问题


#define HOST_NAME "UDP"
#define ADDRESS "127.0.0.1" 
struct UDP_IP_Parameters { 
        uint version; /* e.g. "1.0" = 0x0100 */
        uint port; /* PORT */
        taggedunion {
            "HOST_NAME" char[256];
            "ADDRESS" char[15];
        };
};

int main()
{
struct UDP_IP_Parameters udp;
udp.version = 0x0100;
udp.port = 444;

}

I have created a structure and taggedunion nested within that. Is it possible to define the host name and address as constant like above ?? Is it possible to assign some values by creating a objects for it. Could anyone give me some ideas.


回答1:


That is not C.

No, you can't specify values inside a type declaration.

The closest you can do is probably something like:

typedef struct {
  uint16_t version; /* Guessing size requirements. */
  uint16_t port;
  bool resolved;
  union {
    char host_name[256];
    char address[24];
  } addr;
} UDP_IP_Parameters;

The above uses the resolved flag to "tag" the union, so the program can know which member of the union is valid.

You should be able to initialize an instance like so:

UDP_IP_Parameters so = { 0x100, 80, false, { "stackoverflow.com" } };

Not sure if (in C99) you can use the dotted syntax to do this:

UDP_IP_Parameters so = { 0x100, 80, true, { .address = "198.252.206.16" } };


来源:https://stackoverflow.com/questions/20260730/structure-and-tagged-union-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!