#include <stdio.h>//#define _TEST//toggle display of different structure arrangement, memory space occupancy//----------------------Union definition----------------------typedef union{UnsignedCharUival;//the size of the consortium is 1Byte struct{unsignedCharBit0:1; unsignedCharBit1:1; unsignedCharBit2:1; unsignedCharBIT3:1; unsignedCharBIT4:1; unsignedCharBIT5:1; unsignedCharBIT6:1; unsignedCharBIT7:1; }byte;} myunion;//----------------------structure Definition----------------------typedefstruct{#ifdef _test//variable sort order 1//for DATA0 to open up a 4Byte space, but it itself only occupied 1Byte of the remaining 3Byte//then Data1 tried to store next to Data0 but found only 3Byte and 1Byte no place to store, so it opened up 4Byte space to store their own//finally Data2 found that DATA1 has exclusive 4Byte space itself also re-open 4Byte space//Therefore, the total space occupied is 4+4+4 = 12Byte//where the first 4Byte space only stores 1Byte of variables remaining 3Byte idle//The third 4Byte space also holds 2Byte idle 2ByteUnsignedCharDATA0;//1ByteUnsignedintData1;//4ByteUnsigned Short intDATA2;//2Byte #else //variable sort order 2//for DATA0 to open up a 4Byte space, but it itself only occupied 1Byte of the remaining 3Byte//then Data1 found that DATA0 opened 4Byte space and 3Byte is empty, and itself only need 2Byte space is enough, so close to Data0 storage//finally Data2 found Data0 Data1 in the first 4Byte space has been used to 3Byte only 1Byte space and need 4Byte space, so need to re-open 4Byte space//Therefore, the total space occupied is 4+4 = 8Byte//where the first 4Byte space only stores 3Byte of variables remaining 1Byte idleUnsignedCharDATA0;//1ByteUnsigned Short intData1;//2ByteUnsignedintDATA2;//4Byte #endif}record;//----------------------User Variables----------------------myunion Dataval; RECORD M_record; //Statistical Data//----------------------main function----------------------voidMain () {//----------------------Dataval.uival =0x79; printf ("sizeof_myunion =%d Byte \ n",sizeof(Dataval.uival)); printf ("DataVal.Byte.bit7 =%d \ n", DATAVAL.BYTE.BIT7); printf ("DataVal.Byte.bit6 =%d \ n", DATAVAL.BYTE.BIT6); printf ("DataVal.Byte.bit5 =%d \ n", DATAVAL.BYTE.BIT5); printf ("DataVal.Byte.bit4 =%d \ n", DATAVAL.BYTE.BIT4); printf ("DataVal.Byte.bit3 =%d \ n", DATAVAL.BYTE.BIT3); printf ("DataVal.Byte.bit2 =%d \ n", DataVal.Byte.bit2); printf ("DataVal.Byte.bit1 =%d \ n", DataVal.Byte.bit1); printf ("DataVal.Byte.bit0 =%d \n\n\n", DataVal.Byte.bit0); //----------------------M_RECORD.DATA0 =0x12; M_record.data1=0x34; M_record.data2=0x56; printf ("sizeof_m_record.data0 =%d \ n",sizeof(M_RECORD.DATA0)); printf ("sizeof_m_record.data1 =%d \ n",sizeof(M_RECORD.DATA1)); printf ("sizeof_m_record.data2 =%d \ n",sizeof(M_RECORD.DATA2)); printf ("Sizeof_m_record =%d Byte \ n",sizeof(M_record));}
Test [uinon_struct]