Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Structures and Unions: Custom Types

Lesson 27 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Grouping Related Data

An array lets you store 100 integers. But what if you want to store a "Student Record" which contains a name (string), an age (int), and marks (float)? You need a Structure.

1. Structures (struct)

A structure is a container for multiple variables of different types.

struct Student {
    int id;
    char name[50];
    float gpa;
};

Memory: The size of a structure is roughly the sum of all its members. Each member has its own dedicated space.

2. Unions (union)

Unions look identical to structures, but they work very differently. In a union, all members share the same memory address.

union Data {
    int i;
    float f;
};

Memory: The size of a union is only the size of its largest member. You can only store one value at a time. If you write to i, you overwrite whatever was in f. This is used for memory optimization in systems with very low RAM.

How to Access Members

  • The Dot Operator (.): Used with normal structure variables. s1.id = 101;
  • The Arrow Operator (->): Used when you have a pointer to a structure. ptr->id = 101; (This is shorthand for (*ptr).id).

Padding and Alignment (Advanced)

Compilers often add "hidden" empty bytes between structure members so that they align with the computer's memory boundaries. This makes the CPU faster but the structure larger.

Always use typedef with your structures to save yourself from typing the word "struct" hundreds of times: typedef struct { ... } Student; Now you can just type Student s1; instead of struct Student s1;.