简体   繁体   English

为什么这个C程序的输出是这样的?

[英]Why is the output of this c program like this?

The ouput of the following code is coming out to be 512 0 2 however it should have been 512 0 0. Can somebody please help ! 以下代码的输出结果是512 0 2,但是应该是512 00。请有人帮忙!

 #include<stdio.h>
    int main()
    {
        union a
        {
            int i;
            char ch[2];
        };
        union a z = { 512 };
        printf("%d %d %d\n",z.i, z.ch[0], z.ch[1]);
        return 0;
    }

You have build a union of two bytes. 您已经建立了两个字节的并集。 Know you assign 512d (0x0200) to the union. 知道您为联合分配了512d(0x0200)。
First Byte = 0x00 第一个字节= 0x00
Second Byte = 0x02 第二个字节= 0x02

The integer ( int16_t ) i and your array ch[2] use the same memory! 整数( int16_ti和数组ch[2]使用相同的内存!

Let's assume for simplicity that int is 2 bytes.In this case the memory for your struct will be 2 bytes.Let's also assume that the union is located on address 0x0000.By the results you are getting i can tell you're using a little endian machine - address 0x0000 -> value 0x0000, address 0x0002 -> value 0x0002. 为了简单起见,假设int是2个字节。在这种情况下,结构体的内存将是2个字节。我们还假设并集位于地址0x0000上,通过得到的结果,我可以告诉你使用了一点字节序机器-地址0x0000->值0x0000,地址0x0002->值0x0002。

zi prints 512 correctly. zi正确打印512。

z.ch[0] getting the value from address 0x0000 which is 0 z.ch[0]从地址0x0000获取值为0

z.ch[1] getting the value from address 0x0002 which is 2 z.ch[1]从地址0x0002获取值为2

Big Endian Byte Order: The most significant byte (the "big end") of the data is placed at the byte with the lowest address. 大端字节顺序:数据的最高有效字节(“大端”)放在地址最低的字节处。 The rest of the data is placed in order in the next three bytes in memory. 其余数据按顺序放置在内存的后三个字节中。

Little Endian Byte Order: The least significant byte (the "little end") of the data is placed at the byte with the lowest address. 小尾数字节顺序:数据的最低有效字节(“小尾数”)放在地址最低的字节处。 The rest of the data is placed in order in the next three bytes in memory. 其余数据按顺序放置在内存的后三个字节中。

I think you have some confusion with a struct and a union. 我认为您对结构和联合有些困惑。

A union uses the same memory for all of its members and a struct has a separate memory for each member. 联合对其所有成员使用相同的内存,而结构对每个成员具有单独的内存。

See the following extension of your code (at IDEone ): 请参阅以下代码扩展(在IDEone上 ):

#include<stdio.h>
int main()
{
    union a
    {
        int i;
        char ch[2];
    };
    union a aa = { 512 };
    printf("%d %d %d\n",aa.i, aa.ch[0], aa.ch[1]);

    struct b
    {
        int i;
        char ch[2];
    };
    struct b bb = { 512 };
    printf("%d %d %d\n",bb.i, bb.ch[0], bb.ch[1]);
    return 0;
}

Output: 输出:

Union: 512 0 2
Struct: 512 0 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM