Structure and Union in C

Class12 NEB -Computer Science Exam for Computer Science

Posted by yanib on 2025-03-22 09:25:14 |

Share: Facebook | Twitter | Whatsapp | Linkedin Visits: 199


Structure and Union in C

In C, structure and union are user-defined data types that allow grouping variables of different data types under a single name. However, they work differently in memory allocation.


Structure (struct)

  • A structure is a collection of variables (members) of different types grouped together.

  • Each member has its own memory location.

  • The total memory occupied by a structure is the sum of the memory sizes of all its members.

Example of Structure:

c
#include <stdio.h> // Define a structure struct Student { char name[20]; int age; float marks; }; int main() { struct Student s1 = {"Ram", 20, 85.5}; // Accessing structure members printf("Name: %s\n", s1.name); printf("Age: %d\n", s1.age); printf("Marks: %.2f\n", s1.marks); return 0; }

Memory Allocation for Structure:

If char[20] takes 20 bytes, int takes 4 bytes, and float takes 4 bytes, then total memory used = 28 bytes.


Union (union)

  • A union is similar to a structure, but all members share the same memory.

  • The memory allocated to a union is equal to the size of its largest member.

  • Only one member can store a value at a time.

Example of Union:


#include <stdio.h> // Define a union union Data { int num; float decimal; char ch; }; int main() { union Data d; d.num = 10; printf("Num: %d\n", d.num); d.decimal = 5.5; printf("Decimal: %.1f\n", d.decimal); d.ch = 'A'; printf("Character: %c\n", d.ch); return 0; }

Memory Allocation for Union:

If int takes 4 bytes, float takes 4 bytes, and char takes 1 byte, then the memory allocated = 4 bytes (size of the largest member).


Key Differences Between Structure and Union

FeatureStructure (struct)Union (union)
Memory AllocationEach member gets separate memoryAll members share the same memory
SizeSum of sizes of all membersSize of the largest member
AccessAll members can be accessed at onceOnly one member can hold a value at a time
Example UseStoring multiple values togetherSaving memory when only one value is needed at a time

When to Use?

  • Use struct when you need to store multiple values at the same time.

  • Use union when you need to save memory and only one value is used at a time.

Leave a Comment: