I have the following struct
struct FOO {
int x;
double y;
}
and the array
FOO **manyfoos;
manyfoos = malloc( 10 * sizeof(FOO *) );
After this manyfoos is filled with dynamically allocated FOO * elements
manyfoos[i] = malloc( sizeof(FOO) );
manyfoos[i]->x = x;
manyfoos[i]->y = y;
I now want to sort manyfoos with qsort() and the following compare function
int foocmp(const void * p, const void * q) {
const FOO * pp = (const FOO *)p;
const FOO * qq = (const FOO *)q;
return qq->x - pp->x;
}
Unfortunately the following command is giving unexpected results (qq->x and pp->x are random weird numbers).
qsort(manyfoos, 10, sizeof(FOO *), foocmp);
How can I make this work as expected?
const void *values that are 'really'const FOO **values, notconst FOO *values. If you sort an array ofint, the comparator is givenint *(cast toconst void *). You're sorting an array ofFOO *; therefore, you are givenconst FOO **values cast toconst void *.