If I'm following the example correctly, they use a void **
because it is really a (void *)[]
; an array of untyped memory. The compare function is given two pointers to untyped memory (void *
), and is asked to compare the data.
What you don't understand is that in the first example, your array should be an array of pointers, not an array of values. Your array should look like:
int *val0 = malloc(sizeof(int)); *val0 = 51;
int *val1 = malloc(sizeof(int)); *val1 = 3;
// ... for all values
int *values[] = { val0, val1, val2, ... };
Then the compare function cmp
needs to return a comparison value based on the values, not the pointers that it is given. Code:
int cmp(const void* t1, const void* t2) {
if((const int)(*t1) > (const int)(*t2)) {
return 1;
}
else if((const int)(*t2) > (const int)(*t1)) {
return -1;
}
else {
return 0;
}
}
This way, given pointers to untyped memory, your compare function would find the two integers at those pointers, and compare those values.
The only reason your cmp
function worked with the book's code is because you were telling the sorting function that your array was full of pointers to untyped memory, when it was really just an array of integers. Your comparison function would then be given pointers to memory, which were really just integers, and then compare the pointers as if they were values. In this case, they were.
The reason the book's algorithm uses a void **
is because that way it is generic. The sort
function can take an array holding any data at all, and give the generic data to the compare function, which can dereference the pointers and interpret the data at those addresses however it wishes.