P
pete
David said:[...]
int cmp(const void *i, const void *j)
{
return strcmp(i, j);
}
[...]
char *base[3];
base[0] = string0;
base[1] = string1;
base[2] = string2;
[...]
qsort(base, sizeof base / sizeof*base, sizeof*base, cmp);
Several people have posted code like this now, all apparently without
noticing that it's wrong.
base is an array of pointers to char. This is passed to qsort. qsort
calls cmp with two pointers, each of which points *to an element of
the array*.
Those void *'s in the argument of cmp are "really" char **,
not char *,
and passing them to strcmp produces undefined behavior.
It so happens that you (and the OP) have laid out the program so that
on most platforms strcmp will reach a zero byte somewhere before
faulting, and the conventional layout of automatic storage is such
that strcmp interpreting the addresses as strings will generate the
expected output sort order, so just running the program once to check
it is misleading.
I hate when that happens!
cmp needs to be
int cmp(const void *i0, const void *j0) {
const char *const *i = i0;
const char *const *j = j0;
return strcmp(*i, *j);
}
HTH.
Oops!
Good catch!