C Arrays of Structs
Arrays of Structs
A struct groups related values, like the name and age of one student.
When you want to store many students, you can create an array of structs. Each element in the array is a whole struct:
Example
struct Student {
char name[20];
int age;
};
int main() {
struct Student students[3] = {
{"Liam", 20},
{"Anja", 22},
{"Jenny", 21}
};
printf("%s is %d years old\n", students[0].name, students[0].age);
return 0;
}
Try it Yourself »
Use the index to pick a student, and the dot (.) to pick a member. For example, students[0].name is the name of the first student:
Loop Through an Array of Structs
Use a for loop to print all the students:
Example
struct Student students[3] = {
{"Liam", 20},
{"Anja", 22},
{"Jenny", 21}
};
int i;
for (i = 0; i < 3; i++) {
printf("%s is %d years old\n", students[i].name, students[i].age);
}
Try it Yourself »
Change Values
To change a member, use the index to pick the student, and the dot to pick the member.
In this example, we make two changes: we change the age of the second student (Anja) to 23, and the name of the first student (Liam) to "Lucas":
Example
students[1].age = 23;
strcpy(students[0].name, "Lucas");
printf("%s is %d years old\n", students[0].name, students[0].age);
printf("%s is %d years old\n", students[1].name, students[1].age);
Try it Yourself »
Note: We use = to change the age, because it is a number. For the name, we use strcpy(), because you cannot use = for strings (see Arrays of Strings).
Real-Life Example
Find the student with the highest grade:
Example
struct Student {
char name[20];
int grade;
};
int main() {
struct Student students[4] = {
{"Liam", 78},
{"Anja", 92},
{"Jenny", 85},
{"Olivia", 88}
};
int best = 0;
int i;
for (i = 1; i < 4; i++) {
if (students[i].grade > students[best].grade) {
best = i;
}
}
printf("Top student: %s (%d)\n", students[best].name, students[best].grade);
return 0;
}
Try it Yourself »
The variable best stores the index of the best student so far. The loop compares each student with the best one, and updates best when it finds a higher grade.