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
#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) {
    return strlen(*((const char**)a_lhs)) - strlen(*((const char**)a_rhs));
}

void _print_words(char* const* 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");

    // Q:  What does it mean to pass a function without parentheses.
    // A:  This is a function address.

    // Q:  What segment is that address in?
    // A:  It is in the text segment?
    
    // Q:  Where does qsort(…) come from?
    // A:  Standard C Library (glibc).  It is declared in stdlib.h.

    // Q:  Should HW10 qsort(…) handle strings?
    // A:  No.
    
    // Q:  In the case where the size passed in is less than the size of the
    //     array how should it be handled?

    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.