C – Union

Syntax :

 

Declaration :

 

When we declare a union, memory allocated for a union variable of the type is equal to memory needed for the largest member of it, and all members share this same memory space.

 

 

What is the difference between union and structure?

  • The difference between structure and union is, … 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.

 


Consider the following C declaration, Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment considerations, is (GATE CS 2000)

Answer : 18

Short array s[5] will take 10 bytes as size of short is 2 bytes. When we declare a union, memory allocated for the union is equal to memory needed for the largest member of it, and all members share this same memory space. Since u is a union, memory allocated to u will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8).


 

Predict the output of above program. Assume that the size of an integer is 4 bytes and size of character is 1 byte. Also assume that there is no alignment needed.

 

Answer: Nothing is printed

Explanation: Since x and arr[4] share the same memory, when we set x = 0, all characters of arr are set as 0. O is ASCII value of ‘\0’. When we do “t.arr[1] = ‘G’”, arr[] becomes “\0G\0\0”. When we print a string using “%s”, the printf function starts from the first character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is printed.

 


Reference

 


 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

if you have any queries call us +918300026060 or WhatsApp Dismiss

0

Your Cart

%d bloggers like this: