Array of Structures in C

In C programming language, we can create an array of structures. This is a useful technique for storing and manipulating large amounts of related data. In this article, we will learn how to create an array of structures in C with examples.

How to declare an Array of Structures in C language?

To declare an array of structures, we first need to define the structure. Here is an example of a structure that holds information about a person:

struct Person {
   char name[50];
   int age;
   char address[100];
};

We can now declare an array of Person structures as follows:

struct Person people[3];

Here, we have declared an array of three-person structures. Each structure in the array can hold information about one person, including their name, age, and address.

Initializing an Array of Structures

We can initialize an array of structures just like any other array in C. Here’s an example of how to initialize an array of Person structures:

struct Person people[3] = {
   {"John Smith", 35, "123 Main St"},
   {"Jane Doe", 28, "456 Elm St"},
   {"Bob Johnson", 42, "789 Oak St"}
};

Here, we have initialized an array of three-person structures with information about three people. We can access the members of each structure in the array using the dot operator (.) as follows:

printf("Name: %s\n", people[0].name);
printf("Age: %d\n", people[0].age);
printf("Address: %s\n", people[0].address);

This will print the name, age, and address of the first person in the array.

Iterating over an Array of Structures

We can iterate over an array of structures using a for loop, just like any other array in C. Here’s an example of how to iterate over the array of Person structures we defined earlier and print information about each person:

for (int i = 0; i < 3; i++) {
   printf("Person %d:\n", i + 1);
   printf("Name: %s\n", people[i].name);
   printf("Age: %d\n", people[i].age);
   printf("Address: %s\n\n", people[i].address);
}

This will print the name, age, and address of each person in the array.

Conclusion

Basically, we can create an array of structures to store and manipulate large amounts of related data. Whereas to declare an array of structures, we first need to define the structure. Especially, We can initialize and iterate over an array of structures just like any other array, using the dot operator to access the members of each structure in the array. An array of structures is a useful technique for managing related data and can be used in many different applications.

Categories C

Leave a Comment