C Array of Structures
Syntax
struct structure_name {
data_type member1;
data_type member2;
data_type member3;
...
};
struct structure_name array_name[N];
Example
#include <stdio.h>
struct employee {
char name[50];
int id;
int age;
float salary;
} emp[3];
int main() {
// Employee 1
strcpy(emp[0].name, "John");
emp[0].id = 001;
emp[0].age = 25;
emp[0].salary = 20000.00;
// Employee 2
strcpy(emp[1].name, "Dave");
emp[1].id = 002;
emp[1].age = 30;
emp[1].salary = 30000.00;
// Employee 3
strcpy(emp[2].name, "Mary");
emp[2].id = 003;
emp[2].age = 35;
emp[2].salary = 40000.00;
for(int i=0; i<3; i++) {
printf("Employee %d\n", i+1);
printf("Name: %s\n", emp[i].name);
printf("Id: %d\n", emp[i].id);
printf("Age: %d\n", emp[i].age);
printf("Salary: %.2f\n\n", emp[i].salary);
}
return 0;
}
Output
Employee 1
Name: John
Id: 1
Age: 25
Salary: 20000.00
Employee 2
Name: Dave
Id: 2
Age: 30
Salary: 30000.00
Employee 3
Name: Mary
Id: 3
Age: 35
Salary: 40000.00
Explanation
The C Array of Structures is used to store a collection of non-similar data types. It is defined using the struct
keyword and consists of separate data fields that can be accessed through the structure's name. An array of structures allows you to store multiple structures of the same data type.
Use
You can use an array of structures to store a collection of data that shares common attributes. For example, you can use an array of structures to store employee records that include names, IDs, ages, and salaries. This allows you to efficiently store and access the data for each employee.
Important Points
- An array of structures is a collection of structures that is accessed using an index, just like a regular array.
- Each structure within the array can have different values for each field.
- You can use loops to efficiently modify or access data within an array of structures.
- An array of structures is useful for storing a collection of data that shares common attributes.
Summary
In summary, the C Array of Structures is a powerful tool for storing a collection of data that shares common attributes. It is defined using the struct
keyword and consists of separate data fields that can be accessed through the structure's name. An array of structures allows you to efficiently store and access multiple structures of the same data type, providing a convenient way to manage collections of non-similar data types.