Union and big-endian, littleendian
1. Basic Features of union -- same and different from struct
Union, the Chinese name "consortium, shared body", in a way similar to a structure struct data structure, shared body (union) and struct (struct) it can also contain many data types and variables.
When the members are identical, struct takes up more memory than union.
The reason is that the memory allocation mechanisms of struct and union in C are different:
In struct, all members have their own storage space. To facilitate addressing and management, all data members must follow the memory alignment rules;
In union, all members share a bucket. When operating on different members, the compiler takes different values based on different member types.
2. memory space occupied by union:
#include<stdio.h>union unionTest{ int a; double b;}main(){ union unionTest test; printf("The sizeof of test is %d\n",sizeof(test)); }
Result:
The sizeof of test is 8
Note: The size of memory space allocated by the consortium is the size of the largest member in the consortium.
3. union and big-endian ):
# Include <stdio. h> union var {char c [4]; int I ;};
Int main () {union var data; data. c [0] = 0x04; // because it is of the char type, the number should not be too large, and the ascii range is calculated ~ Data. c [1] = 0x03; // It is written in hexadecimal notation to facilitate direct printing of values in the memory to compare data. c [2] = 0x02; data. c [3] = 0x11; // in the array, the subscript is low and the address is low. The memory content is as follows:, and by address. Four bytes in total!
// Take the four bytes as a whole (regardless of the type, directly print the hexadecimal format), it should be seen from the memory high address to the low address, 0x11020304, set low-level 04 to low-level address. Printf ("% x \ n", data. I );}
Result:
11020304
It indicates that my 32-bit win7 system is a small-end mode.