Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

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

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...