Ioannis Vranos <iv*****@nospam.no.spamfreemail.grwrites:
is*********@gmail.com wrote:
>I wrote a compare function for qsort. I tested version 1 and version
2 (below). Version 1 worked but version 2 did not work. Why?
/*
* Version 1
* Compare two numbers, used in qsort.
*/
int compare(const void *a, const void *b)
{
int *val1, *val2;
val1 = (int *) a;
val2 = (int *) b;
return (*val1 *val2) ? -1 : ((*val1 < *val2) ? 1 : 0);
}
/*
* Version 2
* Compare two numbers, used in qsort.
*/
int compare(const void *a, const void *b)
{
int *val1 = (int *) a, *val2 = (int *) b;
return (*val1 *val2) ? -1 : ((*val1 < *val2) ? 1 : 0);
}
In both versions the function arguments are const void * and you assign
them to int *, instead of const int *.
Yes, and that should be fixed, but that's not going to cause any real
problems in the behavior of qsort(). (Also, the casts aren't
necessary.) As Harald pointed out, both versions appear to be
equivalent.
Also, the OP merely told us that version 2 "did not work". That's not
enough information. *How* did it not work?
--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"