谁能帮我解释一下这段代码的处理过程 [英] Can anyone help me with the explanation of the processing of this snippet of code

查看:43
本文介绍了谁能帮我解释一下这段代码的处理过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其实我是用一个在线的c编译器编译的,代码的输出是5...处理是怎么进行的??

Actually i compiled this in a online c compiler, the output of the code was 5... how did the processing take place??

#include <stdio.h>

int main()
{
    struct ab {char a,b;};
    union abcd
    {
        int c;
        struct ab d;
    }k;
    k.d.a=5;
    k.d.b=0;
    printf("%d",k.c);
}

推荐答案

你有一个整数和一个包含 2 个字符的结构之间的联合.

you have an union between an integer and a structure containing 2 chars.

代码正在更改结构的第一个字符.因为联合,它会影响另一个联合成员的第一个字节,也就是整数.

The code is changing the first char of the structure. Because of the union, it affects the first byte of the other union member, which is the integer.

在小端机器上,将整数的第一个字节设置为 5 会使该整数为 5,这就是您在此处看到的内容.

On a little-endian machine, setting the first byte of an integer to 5 makes this integer 5 and that's what you're seeing here.

在大端机器上,您最终会得到一个非常大的值,具体取决于整数的实际大小.

On a big-endian machine you end up with a very big value depending of the actual size of an integer.

这篇关于谁能帮我解释一下这段代码的处理过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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