如何利用联盟的C语言 [英] How to use Union in C language

查看:158
本文介绍了如何利用联盟的C语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于C语言中的工会问题。
在联合声明的变量将共享相同的内存,好吧,我明白了。
例如,

I have a question about union in C Language. The variables declared in a union will share the same memory, ok, I understand. for example,

union student {
   int i;
   int j;
}x;

我们怎么能访问i和j?
如果我们有:x.i = 1;
然后我们的printf(%d个,J);
会发生什么?编译器错误?
OK,然后怎么样的情况如下:

how could we access the i and j? if we have: x.i = 1; and then we printf("%d",j); what will happen? compiler error? Ok then what about the following case:

union student {
       int i;
       float j;
    }x;

如果我们分配x.i = 2;
什么是x.j的价值?

if we assign x.i = 2; what is the value of x.j?

推荐答案

假设你用

printf("%d", x.j); 

您将看到您分配给 x.i 相同的值,因为这两个变量占用的内存同一地区。它不会是典型使相同类型的两个变量像您已经完成。更典型的是,你会做这个,这样就可以查看相同的数据,但不同的数据类型。

You will see the same value you assigned to x.i, since both variables occupy the same area of memory. It would not be typical to make both variables of the same type like you have done. More typically you would do this so that you can view the same data but as different data types.

想象一下,例如,你想治疗双击既作为双击,有时直接访问位这再次present双(1和0),你会做到这一点与下面的结合。

Imagine for example that you wanted to treat a double both as a double and at times directly access the bits (1s and 0s) that represent the double, you would do that with the following union.

union DoubleData
{
    double d;
    char b[8];
} x;

现在,你可以通过重新present双内存中的8个字节分配/直接通过进入双D 成员或操纵相同的值。

Now you can assign/access the double directly through the d member or manipulate the same value through the 8 bytes that represent the double in memory.

使用您最近更新的问题,

Using your recent update to the question,

union student 
{       
  int i;
  float j;    
}x;

让我们做出有关平台的假设,一个 INT 4字节和浮动是4个字节。在当您访问这种情况下 XJ 你会操纵和治疗4个字节为double,当您访问你将操纵和处理的4个字节作为一个整数。

Lets make an assumption about your platform, an int is 4 bytes and a float is 4 bytes. In this case when you access x.j you will manipulate and treat the 4 bytes as a double, when you access x.i you will manipulate and treat the 4 bytes as an integer.

所以,这两个变量叠加在同一存储区域,但究竟会不同的是你如何跨preT在存储区中的位模式。请记住,任何4个字节的位模式是有效的int,但不是任何4个字节的位模式是有效的float。

So both variables are overlaid in the same memory area, but what will differ is how you interpret the bit pattern in that memory area. Keep in mind that any 4 byte bit pattern is a valid int, BUT not any 4 byte bit pattern is a valid float.

让我们做出有关平台的另一个假设,而int是2个字节,浮点型为4个字节。在这种情况下,当你访问位模式的喜你只会操纵一半是由浮动覆盖,因为在这种情况下,只会部分覆盖 XJ ,因为 XJ 涵盖多个字节。

Lets make another assumption about your platform, and int is 2 bytes and a float is 4 bytes. In this case when you access x.i you will only be manipulating half of the bit pattern that is overlaid by the float, because x.i in this case would only partially overlay x.j since x.j covers more bytes.

这篇关于如何利用联盟的C语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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