Nested structures and arrays of structures

Lesson 6.3: Nested Structures and Arrays of Structures


In previous lessons, you learned about structures and how to access their members. Now, let's explore more advanced ways to use structures by nesting them within each other and creating arrays to hold multiple structures.


1. Nested Structures


What Are They? A nested structure is a structure that is declared as a member of another structure. This allows you to create hierarchical data structures where one structure contains another structure.


Why Use Nested Structures?


Organization: They provide a natural way to model complex real-world objects that are made up of smaller components.

Readability: Nested structures make your code more self-documenting by grouping related data together.

Example:


C

struct Date {

    int day;

    int month;

    int year;

};


struct Employee {

    char name[50];

    int id;

    struct Date birthDate; // Nested structure

};


int main() {

    struct Employee employee1 = {"Alice Johnson", 12345, {25, 12, 1995}};


    printf("Employee Name: %s\n", employee1.name);

    printf("Employee ID: %d\n", employee1.id);

    printf("Birthdate: %d/%d/%d\n", employee1.birthDate.day, employee1.birthDate.month, employee1.birthDate.year);

    return 0;

}

2. Arrays of Structures


What Are They? An array of structures is simply an array where each element is a structure variable. This allows you to store and manage multiple instances of a structure in a convenient way.


Why Use Arrays of Structures?


Efficient Storage: Store a collection of related records (e.g., employee records, student records) in a compact form.

Organized Access: Use array indexing to easily access individual structures and their members.

Example:


C

struct Student {

    char name[50];

    int rollNo;

    float marks;

};


int main() {

    struct Student students[3] = { // Array of 3 Student structures

        {"Alice", 1, 85.5},

        {"Bob", 2, 92.0},

        {"Charlie", 3, 78.3}

    };

 

    for (int i = 0; i < 3; i++) {

        printf("Student %d: Name - %s, Roll No - %d, Marks - %.1f\n", i + 1, students[i].name, students[i].rollNo, students[i].marks);

    }

    return 0;

}

Key Points


Nested Structures:

A structure can contain other structures as members.

Use multiple dot operators (.) to access members of nested structures.

Arrays of Structures:

Create arrays where each element is a structure.

Use array indexing and the dot operator to access structure members.

Exercise


Create a Book structure with members for title, author, and yearPublished.

Create a Library structure that contains an array of Book structures.

Write a program to initialize a Library with several books and then print the details of each book.

Course Syllabus