Optimizing Memory Usage with Nested Unions in C


This program demonstrates the use of a union within a structure, also known as a nested union, in C programming language.

  • The program defines two structures, one is called "store" and the other is called "store2". Both structures have a double type member called "price" and 4 char type members called "name","author","model", and "color" respectively.
  • The first structure "store" is defined with all the members defined individually and the second structure "store2" uses a union to define the same members.
  • A union is a feature of C that allows you to store multiple data types in the same memory location, but only one of them can be active at a time. In this program, the union is used to store the members "name","author","model", and "color" in the same memory location.
  • In the main function, an instance of the structure "store" is created and named as "o". The program assigns values to the members "model" and "color" of structure "o" and then prints the size of the structure "store" using the sizeof() function.
  • Similarly, an instance of the structure "store2" is created and named as "o2". The program assigns values to the members "model" and "color" of structure "o2" using the union and then prints the size of the structure "store2" using the sizeof() function.
  • The output of the program shows that the size of the first structure "store" is 24 bytes and the size of the second structure "store2" is 16 bytes. This difference in size is due to the use of a union in the second structure, which reduces the total memory usage by 8 bytes.
  • It's worth noting that the program is accessing the union members using the dot operator(.) and the arrow operator(->) followed by the union member name.

Source Code

//Shop Management using Structure and Union
#include<stdio.h>
 
//Book -> Name,Author,price
//Cell-> Model,Price,color
struct store
{
    double price;  //8
    char *name;    //4
    char *author;  //4
    char *model;   //4
    char *color;   //4
 
}o;
 
	struct store2
	{
		double price;  //8
		union{
			struct{
				char *name;    //4
				char *author;  //4
			} book;
			 struct{
				char *model;    //4
				char *color;    //4
			} cell;
		}product;
 
	}o2;
 
int main()
{
    o.model="Nokia";
    o.color="Red";
    o.price=3550.00;
    printf("\nSize : %d",sizeof(struct store)); //24
    printf("\nSize : %d",sizeof(struct store2)); //16
    o2.product.cell.model="Nokia";
    o2.product.cell.color="Red";
    o2.price=3550.00;
    return 0;
}
 
To download raw file Click Here

Output

Size : 24
Size : 16

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C