C
Chad
At the following url http://c-faq.com/lib/qsort2.html, they have the
following
Q: Now I'm trying to sort an array of structures with qsort. My
comparison function takes pointers to structures, but the compiler
complains that the function is of the wrong type for qsort. How can I
cast the function pointer to shut off the warning?
A: The conversions must be in the comparison function, which must be
declared as accepting ``generic pointers'' (const void *) as discussed
in question 13.8 above. For a hypothetical little date structure
struct mystruct {
int year, month, day;
};
the comparison function might look like [footnote]
int mystructcmp(const void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
if(sp1->year < sp2->year) return -1;
else if(sp1->year > sp2->year) return 1;
else if(sp1->month < sp2->month) return -1;
else if(sp1->month > sp2->month) return 1;
else if(sp1->day < sp2->day) return -1;
else if(sp1->day > sp2->day) return 1;
else return 0;
}
(The conversions from generic pointers to struct mystruct pointers
happen in the initializations sp1 = p1 and sp2 = p2; the compiler
performs the conversions implicitly since p1 and p2 are void
pointers.)
The question is, why don't you use something like
const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
Chad
following
Q: Now I'm trying to sort an array of structures with qsort. My
comparison function takes pointers to structures, but the compiler
complains that the function is of the wrong type for qsort. How can I
cast the function pointer to shut off the warning?
A: The conversions must be in the comparison function, which must be
declared as accepting ``generic pointers'' (const void *) as discussed
in question 13.8 above. For a hypothetical little date structure
struct mystruct {
int year, month, day;
};
the comparison function might look like [footnote]
int mystructcmp(const void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
if(sp1->year < sp2->year) return -1;
else if(sp1->year > sp2->year) return 1;
else if(sp1->month < sp2->month) return -1;
else if(sp1->month > sp2->month) return 1;
else if(sp1->day < sp2->day) return -1;
else if(sp1->day > sp2->day) return 1;
else return 0;
}
(The conversions from generic pointers to struct mystruct pointers
happen in the initializations sp1 = p1 and sp2 = p2; the compiler
performs the conversions implicitly since p1 and p2 are void
pointers.)
The question is, why don't you use something like
const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
Chad