结构及在C标签联合 [英] Structure and tagged union in c

查看:181
本文介绍了结构及在C标签联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;

}

我已经创建了嵌套的结构和taggedunion。是否有可能定义主机名和地址恒定像上面?是否有可能通过为它创建一个对象分配一些值。任何人都可以给我一些想法。

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.

推荐答案

这不是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" } };

不知道如果(在C99),你可以使用点语法来做到这一点:

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" } };

这篇关于结构及在C标签联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆