03. Arrays of Structs & Nested Struct Composition

🟢 Difficulty: Beginner to Intermediate | In-Memory Database Tables & Multi-Level Object Hierarchies

📖 Definition

An array of structs is an array whose elements are individual structure records, forming an in-memory database table. A nested struct is a structure that contains another structure as one of its internal field members, creating hierarchical object compositions.

🎯 Why It Is Used

  • Database Table Representation: Managing collections of identical records (e.g., an array of 1,000 UserAccount records).
  • Domain Composition: Organizing complex entities naturally (e.g. an Employee struct containing a nested Date birthdate struct and a nested Address struct).

⚙️ How It Works: Chaining Operators

Accessing nested fields chains dot operators together:

employee_list[index].birth_date.year

If the outer entity is accessed via a pointer, combine the arrow operator with dot operators:

emp_ptr->birth_date.year

📝 Syntax

typedef struct {
    int day;
    int month;
    int year;
} Date;

typedef struct {
    int emp_id;
    char name[32];
    Date hire_date; // Nested struct member!
} Employee;

// Array of Structs Initialization
Employee roster[2] = {
    {101, "Alice", {15, 6, 2021}},
    {102, "Bob",   {1, 10, 2022}}
};

🔀 Array of Structs vs Struct of Arrays (AoS vs SoA)

Pattern C Memory Layout Best Use Case
Array of Structs (AoS) [ {id, gpa}, {id, gpa}, {id, gpa} ] General domain modeling, record-by-record processing
Struct of Arrays (SoA) { ids[100], gpas[100] } SIMD vectorization, graphics processing pipelines

🌱 Beginner Example: Array of Structs Iteration

#include <stdio.h>

typedef struct {
    int id;
    char name[20];
    double score;
} Student;

int main(void) {
    Student class_list[3] = {
        {1, "Alice", 92.5},
        {2, "Bob",   85.0},
        {3, "Charlie", 78.0}
    };

    printf("=== Class Roster ===\n");
    for (int i = 0; i < 3; i++) {
        printf("ID: %d | Name: %-8s | Score: %.1lf\n",
               class_list[i].id, class_list[i].name, class_list[i].score);
    }
    return 0;
}

🌼 Intermediate Example: Nested Struct Hierarchies

#include <stdio.h>

typedef struct {
    char street[40];
    char city[20];
    int zip_code;
} Address;

typedef struct {
    char company_name[32];
    Address hq_address; // Nested struct
} Company;

int main(void) {
    Company tech_corp = {
        .company_name = "TechCorp Global",
        .hq_address = {
            .street = "100 Silicon Way",
            .city = "San Jose",
            .zip_code = 95110
        }
    };

    // Chaining member operators: tech_corp.hq_address.city
    printf("Company : %s\n", tech_corp.company_name);
    printf("Street  : %s\n", tech_corp.hq_address.street);
    printf("City/Zip: %s, %d\n", tech_corp.hq_address.city, tech_corp.hq_address.zip_code);
    return 0;
}

🌲 Advanced Example: Searching & Sorting an Array of Structs

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int item_id;
    char title[32];
    double price;
} Product;

// qsort comparator to sort products by price ascending
int compare_products_by_price(const void *a, const void *b) {
    const Product *p1 = (const Product*)a;
    const Product *p2 = (const Product*)b;

    if (p1->price < p2->price) return -1;
    if (p1->price > p2->price) return 1;
    return 0;
}

int main(void) {
    Product inventory[] = {
        {101, "Monitor", 299.99},
        {102, "Keyboard", 49.99},
        {103, "Mouse", 25.50},
        {104, "Headset", 89.99}
    };
    size_t count = sizeof(inventory) / sizeof(inventory[0]);

    qsort(inventory, count, sizeof(Product), compare_products_by_price);

    printf("=== Inventory Sorted By Price (Ascending) ===\n");
    for (size_t i = 0; i < count; i++) {
        printf("ID: %d | Title: %-10s | Price: $%6.2lf\n",
               inventory[i].item_id, inventory[i].title, inventory[i].price);
    }
    return 0;
}

🔍 Line-by-Line Explanation

  • Student class_list[3] = { ... };: Declares a contiguous array storing 3 full Student struct instances.
  • tech_corp.hq_address.city: Chains dot operators to read member fields inside nested structures.
  • const Product *p1 = (const Product*)a;: Casts generic void comparison pointers in qsort() to inspect struct fields for price sorting.

💻 Expected Terminal Output

=== Class Roster ===
ID: 1 | Name: Alice    | Score: 92.5
ID: 2 | Name: Bob      | Score: 85.0
ID: 3 | Name: Charlie  | Score: 78.0
Company : TechCorp Global
Street  : 100 Silicon Way
City/Zip: San Jose, 95110
=== Inventory Sorted By Price (Ascending) ===
ID: 103 | Title: Mouse      | Price: $ 25.50
ID: 102 | Title: Keyboard   | Price: $ 49.99
ID: 104 | Title: Headset    | Price: $ 89.99
ID: 101 | Title: Monitor    | Price: $299.99

⚠️ Common Mistakes & Pitfalls

  • Out-of-Bounds Struct Array Indexing: Accessing class_list[3] on a 3-element array (valid indices 0..2) corrupts adjacent stack memory.
  • Self-Referential Struct Missing Pointer Asterisk: Attempting struct Node { Node next; }; causes an infinite size recursion error. Self-referential structs MUST use pointer members: struct Node *next;.

📌 Important Rules & Limitations

  • Nested structs must be declared before they are used as field types in outer structs.
  • A struct cannot contain an instance of itself directly, but can contain a pointer to an instance of itself.

🌐 Multilingual Explanation: English

An array of structs creates tabular database records. Nested structs combine multiple types hierarchically, accessed by chaining member operators (outer.inner.field).

🌐 Multilingual Explanation: Hindi (Roman Script)

Structs ka array in-memory table banata hai. Nested struct mein ek struct ke andar doosra struct hota hai, jise chain dot operators (outer.inner.field) se access karte hain.

🌐 Multilingual Explanation: Marathi (Roman Script)

Structs cha array mhanje tabular database. Nested struct madhye ekach struct chya aat dusra struct aste (outer.inner.field).

❓ Practice Questions

  1. Why must self-referential structures use pointer members (struct Node *next) rather than direct struct instances?
  2. How do you chain operators to access a nested struct field through an outer struct pointer?
  3. What is the difference between Array of Structs (AoS) and Struct of Arrays (SoA)?

🚀 Practical Coding Challenge

Write a C program named employee_hierarchy.c that defines a Date struct and an Employee struct with nested hire_date, initializes an array of 4 employees, and prints all employees hired after the year 2020.

🧭 Navigation & Breadcrumbs

← Previous: 02. Pointers to Structs | Module 13 Guide | Next: 04. Memory Padding & Alignment →