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 36 37 38 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
// ⚠ Do not use variables called "thing". This is only for effect.
int compare_fn(const void* a_s1, const void* a_s2) {
const char* s1 = *((char**)a_s1);
const char* s2 = *((char**)a_s2);
return strlen(s1) - strlen(s2);
}
void print_array_of_strings(char** strings, size_t num_strings) {
printf("num_strings == %zd\n", num_strings);
for(int i = 0; i < num_strings; i++) {
printf("strings[%d] == \"%s\"\n", i, strings[i]);
}
}
int main(int argc, char* argv[]) {
char* strings[] = { "When", "implemented", "well,", "it", "can" };
size_t num_strings = sizeof(strings) / sizeof(*strings);
print_array_of_strings(strings, num_strings);
qsort(&strings[0], num_strings, sizeof(strings[0]), compare_fn);
print_array_of_strings(strings, num_strings);
/* void qsort(void *base, size_t nmemb, size_t size,
* int (*compar)(const void *, const void *));
*/
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.