使用联合变量分配两个值 [英] Assigning two values with an union variable

查看:26
本文介绍了使用联合变量分配两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量 a 被赋值为 10,变量 b 被赋值为 20,并带有联合变量 v.然后它给出 a 的输出是 20 而不是 10.我不明白.

The variable a is assigned by value 10 and the variable b is assigned by 20 with the union variable v. Then it gives the output of a is 20 instead of 10. I don't get it.

#include<stdio.h>  
int main()  
{
   union var
   {
       int a, b;
   };
   union var v;
   v.a=10;
   v.b=20;
   printf("%d\n", v.a);
   return 0;
}  

我执行了程序,得到了 20 作为输出.

I executed the program and I got 20 as output.

推荐答案

union 将所有列出的成员相互叠加(尽管有些可能比重叠的初始部分延伸得更远),因此分配.a.b 正在写入内存的同一部分.考虑到这一点,输出应该是有意义的.

union overlays all the listed members on top of each other (although some may extend farther than the overlapping initial sections), so assigning to either .a or .b is writing over the same part of memory. With that in mind, the output should make sense.

如果您期望输出为 10,您可能正在考虑 struct 的行为.

You probably were thinking of struct's behavior if you were expecting an output of 10.

在真正扭曲的情况下,可以将不同值的部分同时存储在联合中,但通常部分覆盖的值将被假定为已损坏.例如,这个:

In really twisted scenarios, it's possible to have parts of different values stored in a union simultaneously, but generally the partially overwritten values will be assumed corrupt. For example, this:

union {
    char a;
    struct { char ba; char bb; } b;
} s;

可以同时存储sasbbb,但由于sasbba重叠,分配sa 踩在 sbba 上,这意味着所有 sb 不再值得信赖.

can store s.a and s.b.bb at the same time, but since s.a overlaps s.b.ba, assigning to s.a stomps on s.b.ba, and by implication all of s.b is no longer trustworthy.

用于存储不同类型的联合通常会嵌入到结构中,该结构的第一个成员记录正在使用哪个联合成员:

Often unions intended to store different types will be embedded in a struct whose first member records which union member is in use:

struct {
    int type;
    union {
       char ch;
       int n;
    } datum;
} atom;

此处,type 可能包含一个枚举值,以指示原子中使用的是 datum.ch 还是 datum.n.

Here, type probably would contain an enumerated value to indicate whether datum.ch or datum.n was in use in the atom.

这篇关于使用联合变量分配两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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