Structures and Arrays

Combining structures with arrays in C allows you to manage collections of structured data efficiently. Let's explore how to work with structures and arrays together:

Array of Structures

  • You can create an array of structures to represent a collection of related data.

    struct Point {
        int x;
        int y;
    };
    
    struct Point pointsArray[5];

Here, pointsArray is an array of Point structures.

Initializing Array of Structures

  • You can initialize an array of structures during declaration.

    struct Point pointsArray[] = {{1, 2}, {3, 4}, {5, 6}};

This initializes an array of Point structures with specific values.

Accessing Array of Structures

  • Accessing elements in an array of structures involves using indices and the dot (.) operator.

    pointsArray[0].x = 10;
    pointsArray[0].y = 20;

Looping Through Array of Structures

  • Use loops to iterate through an array of structures.

    for (int i = 0; i < 5; ++i) {
        printf("Point %d: (%d, %d)\n", i + 1, pointsArray[i].x, pointsArray[i].y);
    }

Array Within a Structure

  • You can have an array as a member of a structure.

    struct Student {
        char name[50];
        int grades[3]; // Array of grades
    };
    
    struct Student student1;

Passing Array of Structures to Functions

  • You can pass an array of structures to functions for processing.

    void displayPoints(struct Point arr[], int size) {
        for (int i = 0; i < size; ++i) {
            printf("Point %d: (%d, %d)\n", i + 1, arr[i].x, arr[i].y);
        }
    }

Call the function with displayPoints(pointsArray, 5);.

Arrays of structures provide a versatile way to handle complex data sets. They are especially useful when dealing with collections of similar entities, such as a list of points in a 2D space or a group of students with grades.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!