So... implement the function and be done with it...
int compare_int( const void* a, const void* b )
{
if( *(int*)a == *(int*)b ) return 0;
return *(int*)a < *(int*)b ? -1 : 1;
}
const size_t num_elem = 10;
int elements[num_elem] = { 3, 6, 1, 9, 8, 2, 0, 5, 7, 4 };
qsort( elements, num_elem, sizeof(int), compare_int );
Now your lesson about sorting becomes "how does this work"?
You start by explaining memory layout and arrays. You can't do much in C until you know this anyway.
Then you explain what a void pointer is and why the qsort function needs to know:
- The start address of your array
- The number of elements
- The size of each element
- How to compare the elements
That leads naturally to the comparison function itself... How to cast and dereference types.
Finally, if they are grasping the concepts well, you could point out that the fourth parameter to qsort isn't a special case. You can say it's perfectly okay to have a pointer to a function and pass that as a parameter to another function. It's all about the getting the type of the pointer correct, then the compiler sorts the rest out for you.
int (*comparator)(const void*, const void*) = compare_int;
int a = 1, b = 2;
printf( "comparator(%d, %d) = %d\n", a, b, comparator(&a, &b) );
qsortand passing functions is not where one would normally start when introducing C. Start with what is easy in C, not what is easy in Java.#include <stdio.h>needed to callprintf. Compromises and "magic" are needed to learn a language, everyone has learned to print "hello world" withprintfbefore knowing what is a function...