Chapter13: Structures and Unions

This is one of the most powerful and useful features in C. Structures let you create your own custom data type by grouping different types of data together – like a real-world object.

Think of a structure as a record or form that holds multiple pieces of information about one thing (like a student: name, roll number, marks, grade).

Unions are similar but save memory by sharing the same memory space.

Let’s learn everything in detail.

1. Defining Structures

Syntax:

C

This creates a new data type called struct structure_name.

Example – Defining a Student Structure

C

2. Declaring Structure Variables

You can declare variables in three ways:

Way 1: After definition

C

Way 2: While defining structure (most common)

C

Way 3: Using typedef (very popular – makes code cleaner)

C

3. Accessing Structure Members

Two operators:

  • Dot (.) → when you have the structure variable directly
  • Arrow (->) → when you have a pointer to the structure

Example – Using Dot Operator

C

Output:

text

4. Nested Structures

A structure inside another structure.

Example – Student with Date of Birth

C

Output:

text

5. Array of Structures

Array where each element is a structure – very useful for storing many records.

Example – Store 3 Students

C

6. Pointers to Structures

Use arrow operator (->) to access members.

Example:

C

7. Unions

Union is similar to structure, but all members share the same memory location. Only one member can hold value at a time (saves memory).

Syntax:

C

Example – Union vs Structure

C

Use Cases of Union:

  • When you know only one type of data will be used at a time (e.g., variant types)
  • Memory-critical programs (embedded systems)
  • Type punning (advanced – be careful)

Today’s Homework

  1. Create a structure Book with members: title, author, price, pages. Take input for 3 books and print them.
  2. Make an array of 5 Employee structures (name, id, salary) and find the employee with highest salary.
  3. Create a nested structure Person with Address (street, city, pin) inside it.
  4. Write a program using union to store either an integer or a float (user chooses) and print the value.
  5. Use pointer to structure to change a student’s marks.

You may also like...