C中union的实际用法
可能的重复:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想象一下有一个
struct
来保存一个值和该值的类型。当类型设置为特定类型时,您只需要使用联合成员之一,而不是在同时使用其中一个成员时浪费空间来容纳其中三个成员。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 theunion
rather than waste space for three of them when you use only one simultaneously.我经常使用它的地方:解析配置文件,我将所有值存储在联合数据类型中。例如,当值可以是 int 类型或字符串时,我会使用如下数据结构:
在更复杂的问题中,我也使用它们。例如,有一次我为一种简单的脚本语言编写了一个解释器,该语言中的值由包含联合的结构表示。
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:
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.