Ask a Question

Difference between structure and union in c programming and exam


Spooky

on 2017-05-25 18:51:28  

Consider a same-to-same structure and union, both contain say 3 elements : (1).an integer (4-bytes); (2) char array of length=3 (3-bytes); and ;(3) a float value (say 8-byte) . Now a structure when initialized will be allocated total of 4+3+8=15 bytes of ram. But when the same is declared inside a Union, only the element with largest memory required i.e (3) float in this case with 8-byte of ram will be assigned to the union because it can only represent any ONE of its element at a time. It may assigned to an integer, a float or a char array of size 3. Structures can contain all 3 values at a time.

Spooky

on 2017-05-25 18:58:52  

Think of Union as the OR operation. so a union is OR of its element ;1 or 2 or 3.......Only one of them. BUT.. Structure is like AND. so structure contains elements 1 and 2 and 3.... all of them at a time.