Question 13.8

I'm trying to sort an array of strings with qsort, using strcmp as the comparison function, but it's not working.


By ``array of strings'' you probably mean ``array of pointers to char.'' The arguments to qsort's comparison function are pointers to the objects being sorted, in this case, pointers to pointers to char. strcmp, however, accepts simple pointers to char. Therefore, strcmp can't be used directly. Write an intermediate comparison function like this:

/* compare strings via pointers */
int pstrcmp(const void *p1, const void *p2)
{
	return strcmp(*(char * const *)p1, *(char * const *)p2);
}

The comparison function's arguments are expressed as ``generic pointers,'' const void *. They are converted back to what they ``really are'' (char **) and dereferenced, yielding char *'s which can be passed to strcmp. (Under a pre-ANSI compiler, declare the pointer parameters as char * instead of void *, and drop the consts.)

(Don't be misled by the discussion in K&R2 Sec. 5.11 pp. 119-20, which is not discussing the Standard library's qsort).

References: ANSI Sec. 4.10.5.2
ISO Sec. 7.10.5.2
H&S Sec. 20.5 p. 419


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback