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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Forward declarations
static int _compare_strings(const void* a_s1, const void* a_s2);
void _print_strings(char* strings[], size_t num_strings);
int main(int argc, char* argv[]) {
// Create array of sample strings to be sorted
char* sample_strings[] = { "banana", "cherry", "apple" };
size_t num_strings = sizeof(sample_strings)/sizeof(sample_strings[0]); // == 3
// Print the list, unsorted
printf("Before sort\n");
_print_strings(sample_strings, num_strings);
// SORT
qsort(sample_strings, num_strings, sizeof(sample_strings[0]), _compare_strings);
// Print the list, sorted
printf("After sort\n");
_print_strings(sample_strings, num_strings);
return EXIT_SUCCESS;
}
int _compare_strings(const void* a1, const void* a2) {
// Step 1: Convert void* arguments (address of anything) to a type
// that is relevant to what we are sorting. Since we are
// sorting strings (char*), we need to convert the arguments
// to char**.
//
// Remember that the arguments are the address of the thing we are
// sorting. If we were sorting integers we would convert the
// void* arguments to int*.
char** a_s1 = (char**)a1;
char** a_s2 = (char**)a2;
// Step 2: Dereference the addresses of strings (char**) to get the strings
// we are trying to compare (char*).
char* s1 = *a_s1;
char* s2 = *a_s2;
// Step 3: Do the comparison.
int result = strcmp(s1, s2);
// If result < 0, it means s1 < s2
// If result == 0, it means s1 == s2
// If result > 0, it means s1 > s2
return result;
//// Equivalent to...
//return strcmp(*((const char**)a1), *((const char**)a2));
// Note: const is just tells the compiler that you do not intend to
// modify it. That way, the compiler can warn you if you do.
}
void _print_strings(char* strings[], size_t num_strings) {
// Print all strings
for(int i=0; i < num_strings; i++) {
// Print one string
printf(" strings[%d] == \"%s\"\n", i, strings[i]);
}
}
|
© Copyright 2016 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.