Can anyone help me with the explanation of the processing of this snippet of code

落爺英雄遲暮 提交于 2019-12-12 06:58:37

问题


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);
}

回答1:


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.

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.



来源:https://stackoverflow.com/questions/56102678/can-anyone-help-me-with-the-explanation-of-the-processing-of-this-snippet-of-cod

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!