Array of structs
- C course
- Intermediate
- Lesson 34/116
- 5 min
Learn arrays of structs and sorting them.
Array of structs
The natural way to manage multiple structs is an array of structs. This is the core pattern for record lists, tables and collections.
Example: struct Person people[3];. Access: people[0].age = 30;. Here people[0] is a struct value; that's why the . operator is used. The array size must be fixed; dynamic size needs a pointer and malloc. Looping through all elements is common: for (int i = 0; i < 3; i++) printf("%d\n", people[i].age);.
Sorting with qsort
To sort an array of structs, you can use the standard qsort function. qsort takes a comparator callback; this combines the function pointer concept with structs.
Call: qsort(people, 3, sizeof(struct Person), compare);. Comparator signature: int compare(const void *a, const void *b). Inside you cast the pointer to struct Person*: struct Person *pa = (struct Person*)a;. Then return pa->age - pb->age. This pattern gives ascending sort by age.
Practice Print a struct array
Define struct Person with char name[32]; and int age;. In main, declare struct Person people[3] = {{"Ali", 30}, {"Ayşe", 25}, {"Veli", 35}};. With a for loop, print each element's age field with printf("%d\n", people[i].age);.
Starter code
#include <stdio.h>
// Define struct Person (name[32] and age)
// In main declare a 3-element people array and initialize
// Loop with for and print each element's age
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
struct Person {
char name[32];
int age;
};
int main(void) {
struct Person people[3] = {{"Ali", 30}, {"Ayşe", 25}, {"Veli", 35}};
for (int i = 0; i < 3; i++) {
printf("%d\n", people[i].age);
}
return 0;
}Expected output
30 25 35
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the array expressions
| Term | Meaning |
|---|---|
people[0].age |
First element's field |
people[i] |
Indexed element |
struct Person people[3] |
Array declaration |
people[2].name |
Last element's field |
2 Assign a field of an array element
struct Person people[3];
people[0]____ = 30;
struct Person people[3];
people[0].age = 30;
Explanation: people[0] is a value; access with .age.
3 To sort a struct array by age?
- strcpy
- malloc
- fopen
- qsort + comparator Correct answer
Explanation: qsort takes a comparator callback and sorts the struct array.