Arrays of structures and nested structures provide powerful ways to organize and manage complex data in C, enabling the representation and manipulation of sophisticated data structures. Let’s explore these concepts with examples.

1. Array of Structures

An array of structures allows you to store multiple instances of a structured data type in a sequential manner. Each element of the array is an instance of the structure.

Example:

#include <stdio.h>

// Define a structure representing a point in 2D space
struct Point {
    int x;
    int y;
};

int main() {
    // Declare an array of structures
    struct Point points[3];
    
    // Initialize the array elements
    points[0].x = 1;
    points[0].y = 2;
    points[1].x = 3;
    points[1].y = 4;
    points[2].x = 5;
    points[2].y = 6;
    
    // Access and print the values
    for (int i = 0; i < 3; i++) {
        printf("Point %d: x = %d, y = %d\n", i + 1, points[i].x, points[i].y);
    }
    
    return 0;
}

In this example, the Point structure represents a point in 2D space. An array of Point structures is declared, and its elements are initialized. The program prints the coordinates of each point in the array.

2. Structure within a Structure (Nested Structure)

A nested structure contains members that are themselves structures, allowing you to model more complex relationships and represent hierarchical data structures.

Example:

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

// Define a structure representing a date
struct Date {
    int day;
    int month;
    int year;
};

// Define a structure representing a person
struct Person {
    char name[50];
    int age;
    struct Date birthdate; // Nested structure
};

int main() {
    // Declare a structure variable of type Person
    struct Person person1;
    
    // Initialize the values
    strcpy(person1.name, "John Doe");
    person1.age = 25;
    person1.birthdate.day = 15;
    person1.birthdate.month = 7;
    person1.birthdate.year = 1998;
    
    // Access and print the values
    printf("Person: %s, Age: %d\n", person1.name, person1.age);
    printf("Birthdate: %d-%d-%d\n", person1.birthdate.day, person1.birthdate.month, person1.birthdate.year);
    
    return 0;
}

In this example, the Date structure represents a date, and the Person structure represents a person, including a nested Date structure to represent the birthdate. The program initializes a Person structure and prints the person’s details, including their birthdate.

Summary

  • Array of Structures: Allows you to store multiple instances of a structure, making it easy to manage collections of related data.
  • Nested Structures: Enables you to define structures within structures, allowing for the representation of complex, hierarchical data.

These features enhance the flexibility and power of C when dealing with complex data types, improving the organization and readability of your code.

# Written by Elliyas Ahmed