I have an assignment from a professor that I don't fully understand. This is our specified function header:
PQueue createQueue( int (*cmp)(const void*a, const void*b) ) {
I can't find the documentation for cmp to understand what the function itself does; what does it do?
And beyond that, how can I refer to it within createQueue when I write the code to create the queue?
cmp
is parameter of createQueue
, it is a function pointer passed in by the caller. Typically cmp
it will return:
*a
is less than *b
*a
is equal to *b
*a
is greater than *b
This is the convention used by the standard library qsort
, which sorts an array when given some comparison function.
As a concrete example, we can get the behavior
int a = 1, b = 2, c = 2;
cmp(&a, &b); // returns < 0
cmp(&b, &c); // returns 0
cmp(&b, &a); // returns > 0
if we define cmp as
int cmp(const void * a, const void * b) {
const int * a_int_ptr = (const int *)a;
const int * b_int_ptr = (const int *)b;
int a_value = *a_int_ptr;
int b_value = *b_int_ptr;
return a_value - b_value;
}