Function Pointers and Callbacks with qsort in C
We discussed function pointers earlier, and here's an example that demonstrates their usage with the qsort function to sort an array of strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compareStrings(const void* a, const void* b) {
const char* str1 = *(const char**)a;
const char* str2 = *(const char**)b;
return strcmp(str1, str2);
}
int main() {
char* strings[] = {"apple", "banana", "cherry", "date", "elderberry"};
int stringCount = sizeof(strings) / sizeof(strings[0]);
qsort(strings, stringCount, sizeof(char*), compareStrings);
printf("Sorted strings:\n");
for (int i = 0; i < stringCount; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
No comments:
Post a Comment