Sort String Arrays in C: Complete Guide
In the C language, the library function qsort() can be used to sort an array of strings.
The prototype of the qsort() function is:
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
The base is the starting address of the array to be sorted, nmemb is the number of elements in the array, size is the size of each element, and compar is a pointer to the comparison function.
The prototype of the comparison function is:
int compar(const void *a, const void *b);
In which, a and b are pointers pointing to the elements being compared, the comparison function should return an integer value.
- If the return value is less than 0, then a should come before b.
- If the return value is greater than 0, then a should come after b.
- If the return value is 0, the relative order of a and b will remain unchanged.
Here is an example code demonstrating how to use the qsort() function to sort an array of strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
return strcmp(*(char **)a, *(char **)b);
}
int main() {
char *array[] = {"apple", "banana", "orange", "grape", "lemon"};
int length = sizeof(array) / sizeof(array[0]);
qsort(array, length, sizeof(array[0]), compare);
for (int i = 0; i < length; i++) {
printf("%s\n", array[i]);
}
return 0;
}
The output result is:
apple
banana
grape
lemon
orange
In this example, an array of strings called “array” containing five strings is sorted using the qsort() function, resulting in the strings being sorted in alphabetical order.