#include <stdio.h>
int main () {
union{
int ig[4];
Char a[8];
} t;
T.ig[0] = 0x4241;
T.IG[1] = 0x4443;
T.IG[2] = 0x4645;
T.IG[3] = 0x0000;
printf ("\n%s\n", t.a);
return 0;
}
First look at the results:
It's very nice to be here.
Try the following program:
#include <stdio.h>
int main () {
union{
int ig[4];
Char a[8];
} t;
T.ig[0] = 0x4241;
T.IG[1] = 0x4443;
T.IG[2] = 0x4645;
T.IG[3] = 0x0000;
printf ("\n%s\n", t.a);
printf ("%d\n", sizeof (t));
return 0;
}
Results:
As you can see, the union length is 16, and you can infer that the int in the Union is 4 bytes and char is a byte (this is known to all C).
Try the following program:
#include <stdio.h>
int main () {
union{
int ig[4];
Char a[8];
} t;
T.ig[0] = 0x4241;
T.IG[1] = 0x4443;
T.IG[2] = 0x4645;
T.IG[3] = 0x0000;
printf ("\n%s\n", t.a);
printf ("%d\n", sizeof (t));
return 0;
}
Results:
As you can see, the result is AB, because in 0x4241, 41 is stored in the low, that is, the head address of the IG array, which first outputs 0x41 (A) and then outputs 0x42 (B)
But the t.ig[1] = 0x4443 Note removed, found that the result is still ab,why? later thought, each element is 32 bits, and 0x4241 only occupy 16 bits, the back 16 is empty, so that when the second 8 digits, because no content, then stop reading, All subsequent assignments, even for other elements in the IG array, are not exported.
You can try this by using the following procedure:
#include <stdio.h>
int main () {
union{
int ig[4];
Char a[8];
} t;
T.ig[0] = 0x44434241;
T.IG[1] = 0x4443;
T.IG[2] = 0x4645;
T.IG[3] = 0x0000;
printf ("\n%s\n", t.a);
printf ("%d\n", sizeof (t));
return 0;
}
Results:
Can see the completion of ig[0] After the 16, the result is ABCDCD, this time to understand.