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
39
40
41
42
43
44
45
46
47
48
49
50
51
#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 = *((char**)a_lhs);
    const char* rhs = *((char**)a_rhs);
    size_t len_lhs = strlen(lhs);
    size_t len_rhs = strlen(rhs);
    return len_lhs - len_rhs;
}

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");

    // Same as `qsort(&(words[0]), 5, 8, …)` which means:
    //   "sort an array of 5 chunks of memory, 8 bytes each.

    /*
    void qsort(void *base, size_t nmemb, size_t size,
               int (*compar)(const void *, const void *));

    The comparison function must return an integer less than, equal  to,  or
    greater than zero if the first argument is considered to be respectively
    less than, equal to, or greater than the second.  If two members compare
    as equal, their order in the sorted array is undefined.
    */

    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.