Array of Structures and Structure within a Structure (Nested Structure) in C
Arrays of structures and nested structures provide a way to organize and manage complex data in C, allowing you to represent and work with more sophisticated data structures.
Let's explore examples of an array of structures and a structure within a structure (nested structure) in C.
1. Array of Structures:
In C, a structure is a user-defined data type that allows you to group together different types of variables under a single name. An array of structures is a collection of these structured data types arranged in a sequential manner. Each element of the array is an instance of the structure.
#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, we define a structure Point
representing a point in 2D space. Then, we declare an array of Point
structures and initialize its elements. The program prints the coordinates of each point in the array.
2. Structure within a Structure (Nested Structure):
A structure in C can contain members that are themselves structures. This concept is known as a nested structure. It allows you to model more complex relationships and represent hierarchical data structures.
#include <stdio.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, we define two structures: Date
for representing a date and Person
for representing a person. The Person
structure contains a nested structure (Date
) to represent the birthdate. The program initializes a Person
structure and prints the person's information, including the birthdate.
These examples illustrate how to work with arrays of structures and structures within structures in C.