+ 4

Whats the difference between union and structure?

4th Dec 2016, 11:17 AM
sadiya zainab
sadiya zainab - avatar
2 Respostas
+ 2
The difference between structure and union is, 1. The amount of memory required to store a structure variable is the sum of the size of all the members. On the other hand, in case of unions, the amount of memory required is always equal to that required by its largest member.
4th Dec 2016, 11:34 AM
Kaushali
Kaushali - avatar
+ 2
In simple word Not speaking technically: Assumption: chair = memory block , people = variable Structure : If there are 3 people they can sit in chair of their size correspondingly . Union : If there are 3 people only one chair will be there to sit , all need to use the same chair when they want to sit . Technically speaking means : The below mentioned program gives a deep dive into structure and union together . struct MAIN_STRUCT { UINT64 bufferaddr; union{ UINT32 data; struct INNER_STRUCT{ UINT16 length; UINT8 cso; UINT8 cmd;} flags;} data1;}; Total MAIN_STRUCT size =sizeof(UINT64) for bufferaddr + sizeof(UNIT32) for union + 32 bit for padding(depends on processor architecture) = 128 bits . For structure all the members get the memory block contiguously . Union gets one memory block of the max size member(Here its 32 bit) . Inside union one more structure lies(INNER_STRUCT) its members get a memory block of total size 32 bits(16+8+8) . In union either INNER_STRUCT(32 bit) member or data(32 bit) can be accessed .
4th Dec 2016, 11:42 AM
Aditya kumar pandey
Aditya kumar pandey - avatar