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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
// REMINDER: DO NOT COPY CODE FROM ANYWHERE --- INCLUDING THIS SNIPPET ---
// unless Prof. Wang or I have explicitly marked it as "okay to copy/adapt"
// or similar. Chance similarity is not a problem, but do not look at this
// snippet or any other code that is not allowed while writing your own code.
int compare_fn(const void* a_lhs, const void* a_rhs) {
const char* lhs_string = *((char**)a_lhs);
const char* rhs_string = *((char**)a_rhs);
return strlen(lhs_string) - strlen(rhs_string);
}
void _print_words(const char** words, size_t num_words, const char* label) {
printf("\n%s\n", label);
for(int i = 0; i < num_words; i++) {
printf("\"%s\"\n", words[i]);
}
}
int main(int argc, char* argv[]) {
char* words[] = { "from", "Jack", "McBrearty", "to", "everyone" };
size_t num_words = sizeof(words) / sizeof(*words);
// This works only on arrays declared with square brackets.
_print_words(words, num_words, "BEFORE");
qsort(&(words[0]), num_words, sizeof(words[0]), compare_fn);
_print_words(words, num_words, "AFTER");
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.