问题
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