In addition to dbush excellent answer, it should be noted that the case of an alternate comparison function with a prototype of int cmp(const char *s1, const char *s2)
, such as strcmp
is not as clear cut as the one in the question. The C Standard specifies that:
6.2.5 Types
[...] A pointer to void
shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.
So pointers to functions with prototypes int cmp(const void *v1, const void *v2)
and int cmp(const char *v1, const char *v2)
are not compatible but the calling sequence is quite unlikely to be different even on those extremely rare targets where int cmp(const double *v1, const double *v2)
would be problematic (early Cray systems and CPUs lacking byte addressability).
You do not provide the code for the comparison functions: it is a common mistake to simply return the difference of values (*d1 - *d2
). This does not work for floating point values and neither does it for int
values as the subtraction may overflow.
Here is an implementation for increasing order that works for all number types:
int cmp(const void *v1, const void *v2) {
const int *p1 = v1, *p2 = v2;
return (*p1 > *p2) - (*p1 < *p2);
}
For floating point types, special handling of NaN values may be needed:
// sort by increasing values, with NaN after numbers
int cmp(const void *v1, const void *v2) {
const double *p1 = v1, *p2 = v2;
if (isnan(*p1)) {
return isnan(*p2) ? 0 : 1;
} else
if (isnan(*p2)) {
return -1;
} else {
return (*p1 > *p2) - (*p1 < *p2);
}
}