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 | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int compare_integers(const void* lhs, const void* rhs) {
const int* lhs_int = lhs; // No type cast needed to assign a
const int* rhs_int = rhs; // void* to a ▒▒▒* in C.
fprintf(stderr, "// compare_integers(&%d, &%d)\n", *lhs_int, *rhs_int);
if(*lhs_int < *rhs_int) {
return -1; // if the lhs number is less than the rhs number
}
else if(*lhs_int == *rhs_int) {
return 0; // equal
}
else { // greater
return 1;
}
}
int main(int argc, char* argv[]) {
/* void qsort(void *base, size_t nmemb, size_t size, */
/* int(*compar)(const void *, const void *)); */
int array[] = {3, 5, 1};
int num_elements = sizeof(array) / sizeof(array[0]); // == 3
// 12 / 4 // on our platform
// Sort an *ARRAY* of integers.
qsort(array, num_elements, sizeof(array[0]), compare_integers);
// Same as:
//qsort(array, 3, 4, compare_integers);
for(int i = 0; i < num_elements; i++) {
printf("%d\n", array[i]);
}
assert( *array == array[0] );
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2019 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.