11.2.6 Definition of comparison functions bsearch and qsort in K&R format
When the definition of comparison function bsearch or qsort is written in the K&R format, the caller side of comparison function bsearch or qsort passes the argument as a near pointer but the defining side of the comparison function generates an assembler code in which the formal parameter is received as a far pointer. Therefore, the program will not operate correctly.
#include <stdlib.h>
int table[5] = {0, 1, 2, 3, 4}, key = 3, *ret;
int compare();
void func(void) {
ret = bsearch(&key, table, 5, sizeof(int), compare);
}
int compare(i, j)
int *i, *j;
{
if (*i > *j) {
return 1;
}
else if (*i < *j) {
return -1;
}
return 0;
}
|
(Workaround)
Write the definition and declaration of comparison function bsearch or qsort in the function prototype format.
#include <stdlib.h>
int table[5] = {0, 1, 2, 3, 4}, key = 3, *ret;
int compare(int *, int *); // Function prototype
void func(void) {
ret = bsearch(&key, table, 5, sizeof(int), compare);
}
int compare(int *i, int *j) // Function prototype
{
if (*i > *j) {
return 1;
}
else if (*i < *j) {
return -1;
}
return 0;
}
|