Sorting an array of structs
What you'll learn: How to use the qsort function to organize a collection of structures based on a specific member variable.
Imagine you have a stack of index cards, where each card represents a Student. Each card has a name and a grade. If you want to sort these cards by grade, you don't just move the grades around; you move the entire card. Sorting an array of structs in C follows this same logic: we swap entire blocks of data based on a comparison of one specific field.
The Comparison Logic
To sort an array, C needs to know how to compare two elements. Since a struct contains multiple pieces of data, you must define a "comparison function." This function tells C: "Look at the grade member of these two students and tell me which one is higher."
The standard library provides a powerful tool called qsort. It requires four things: the array, the number of elements, the size of one element, and your custom comparison function.
Code Example: Sorting Students by Grade
In this example, we will sort an array of Student structs in descending order (highest grade first).
#include <stdio.h>
#include <stdlib.h> // Required for qsort
struct Student {
char name[20];
int grade;
};
// The comparison function
int compareStudents(const void *a, const void *b) {
// 1. Cast the pointers to our struct type
struct Student *studentA = (struct Student *)a;
struct Student *studentB = (struct Student *)b;
// 2. Return a positive, negative, or zero value
// For descending order: B - A
return (studentB->grade - studentA->grade);
}
int main() {
struct Student classroom[3] = {
{"Alice", 85},
{"Bob", 98},
{"Charlie", 72}
};
// qsort(array, count, size_of_element, comparison_function)
qsort(classroom, 3, sizeof(struct Student), compareStudents);
printf("Top Student: %s with %d\n", classroom[0].name, classroom[0].grade);
return 0;
}
How it works
The qsort function is "type-blind"—it treats your array as a series of raw bytes. This is why we use void * pointers in our comparison function. Inside that function, we cast those pointers back to struct Student so we can access the .grade member.
If the function returns a negative number, studentA comes first. If it returns a positive number, studentB comes first. By subtracting the grades, we create a simple logic that allows qsort to shuffle the entire struct—name and grade together—into the correct position.
Key takeaway
To sort structs, use qsort with a custom comparison function that casts void pointers to your struct type and compares the desired member.