C中union的实际用法

发布于 2024-11-15 04:58:19 字数 275 浏览 9 评论 0原文

可能的重复:
C:联合在哪里实际使用?

我知道 union 的概念,但我在现实世界编码中没有看到我应该使用联合数据结构的实际情况。如果你们能给我一些示例或教程来展示正确使用联合的案例,我将非常感激。

提前致谢。

Possible Duplicate:
C: Where is union practically used?

I know the concept of union but I don't see the actual case in real world coding that I should use union data structure. I will be very appreciated if you guys can give me some examples or tutorials that shows cases using union properly.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江心雾 2024-11-22 04:58:19

想象一下有一个struct来保存一个值和该值的类型。当类型设置为特定类型时,您只需要使用联合成员之一,而不是在同时使用其中一个成员时浪费空间来容纳其中三个成员。

struct {
  int type;

  union {
    int intval;
    double dval;
    char cval;
  } value;
}

Imagine having a struct that keeps a value and the type of that value. When the type is set to a particular type, you would only need to use one of the members of the union rather than waste space for three of them when you use only one simultaneously.

struct {
  int type;

  union {
    int intval;
    double dval;
    char cval;
  } value;
}
如果没有你 2024-11-22 04:58:19

我经常使用它的地方:解析配置文件,我将所有值存储在联合数据类型中。例如,当值可以是 int 类型或字符串时,我会使用如下数据结构:

struct cval_s {
  short type;
  union {
    int ival;
    char *cval;
  } val;
};

在更复杂的问题中,我也使用它们。例如,有一次我为一种简单的脚本语言编写了一个解释器,该语言中的值由包含联合的结构表示。

Where I use it constantly: parsing a configuration file I store all values in a union data type. E.g. when values can be int types or strings, I would use a data structure as follows:

struct cval_s {
  short type;
  union {
    int ival;
    char *cval;
  } val;
};

In complexer problems, I use them, too. E.g. once I wrote an interpreter for an easy scripting language, and a value in this language was represented by a struct containing a union.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文