1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
void print_strings(char* label, char** strings, size_t length) {
printf("\n\n%s\n", label);
for(size_t i = 0; i < length; i++) {
printf("%s\n", strings[i]);
}
printf("\n");
}
int compare_fn(void const* a_lhs, void const* a_rhs) {
// return negative if *a_lhs < *a_rhs
// zero if =
// positive if >
char* const* a_lhs_str = a_lhs;
char* const* a_rhs_str = a_rhs;
return strcmp(*a_lhs_str, *a_rhs_str);
}
int main(int argc, char* argv[]) {
char* strings[] = { "alpha", "charlie", "foxtrot", "bravo", "echo", "delta" };
size_t size_of_one = sizeof(strings[0]); // size of a char* is 8 on our platform
size_t number_of_elements = sizeof(strings) / size_of_one;
print_strings("BEFORE sorting", strings, number_of_elements);
qsort(strings, number_of_elements, size_of_one, compare_fn);
print_strings("AFTER sorting", strings, number_of_elements);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2021 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.