【问题标题】:Unions and values stored存储的联合和值
【发布时间】:2022-11-10 18:30:00
【问题描述】:

我知道union 允许在同一个内存位置存储不同的数据类型。您可以定义具有许多成员的联合,但在任何给定时间只有一个成员可以包含值。考虑这个程序:

    #include <stdio.h>

    union integer {

         short s;
         int i;
         long l;
    };

    int main() {

         union integer I;

         scanf("%hi", &I.s);
         scanf("%d", &I.i);
         scanf("%ld", &I.l);

         printf("%hi - %d - %ld ", I.s, I.i, I.l );
    }

假设我们输入值115513,程序将作为输出

13 - 13 - 13,这里没问题。但是,如果我要创建 struct integer 类型的三个不同变量

    #include <stdio.h>

    union integer {

         short s;
         int i;
         long l;
    };

    int main() {

         union integer S;
         union integer I;
         union integer L;

         scanf("%hi", &S.s);
         scanf("%d", &I.i);
         scanf("%ld", &L.l);

         printf("%hi - %d - %ld ", S.s, I.i, L.l );
    
    }

比所有值都将被保留。 怎么来的?通过使用三个变量,我实际上是在使用三个联合,每个联合只包含一个值吗?

【问题讨论】:

  • 不同的联合是不同的变量
  • 对,那是正确的。每个工会都独立于其他工会。您不必利用每个工会成员。

标签: c union


【解决方案1】:

同一个变量的union成员sil共享同一个内存。读取与上次写入不同的成员是未定义的行为。

如果您定义 3 个相同 union 类型的变量,则与定义 3 个 int 类型的变量没有太大区别。每个变量都有自己的内存,每个变量只能保存union 成员之一。

【讨论】:

    猜你喜欢
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多