How to Use Array of Structures in C: Syntax and Example
In C, you can create an
array of structures by first defining a struct type and then declaring an array of that type. Each element in the array holds a separate structure instance, allowing you to store multiple related data items together.Syntax
To use an array of structures in C, you first define a struct with the fields you want. Then, declare an array of that struct type. You can access each structure in the array using its index and access fields with the dot operator.
- struct definition: defines the data layout
- array declaration: creates multiple structure instances
- access: use
array[index].fieldto read or write data
c
struct Person {
char name[50];
int age;
};
struct Person people[3];Example
This example shows how to declare an array of 3 Person structures, assign values to each, and print their details.
c
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person people[3];
// Assign values
strcpy(people[0].name, "Alice");
people[0].age = 30;
strcpy(people[1].name, "Bob");
people[1].age = 25;
strcpy(people[2].name, "Charlie");
people[2].age = 20;
// Print details
for (int i = 0; i < 3; i++) {
printf("Name: %s, Age: %d\n", people[i].name, people[i].age);
}
return 0;
}Output
Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Charlie, Age: 20
Common Pitfalls
Common mistakes when using arrays of structures include:
- Forgetting to include
string.hwhen usingstrcpyto copy strings. - Accessing array elements out of bounds, which causes undefined behavior.
- Using the assignment operator
=to copy strings instead ofstrcpy. - Not initializing all elements before use.
Example of wrong and right way to copy strings:
c
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person p;
// Wrong: p.name = "Alice"; // This causes error
// Right:
strcpy(p.name, "Alice");
p.age = 30;
printf("Name: %s, Age: %d\n", p.name, p.age);
return 0;
}Output
Name: Alice, Age: 30
Quick Reference
Tips for using arrays of structures in C:
- Define the
structfirst with all needed fields. - Declare an array of that
structtype to hold multiple items. - Use
strcpyto copy strings into character arrays inside structs. - Access elements with
array[index].field. - Always check array bounds to avoid errors.
Key Takeaways
Define a struct type before creating an array of that struct.
Use array indexing and dot operator to access individual structure fields.
Use strcpy to copy strings into struct character arrays, not assignment.
Always initialize all elements in the array before use.
Avoid accessing elements outside the array bounds to prevent errors.