Function-types: compatability, and typedefs

Richard O'Keefe ok at cs.mu.oz.au
Fri Sep 1 21:08:29 AEST 1989


In article <19361 at mimsy.UUCP>, chris at mimsy.UUCP (Chris Torek) writes:
> In article <KERS.89Aug31164048 at cdollin.hpl.hp.com> kers at hpld.hpl.hp.com
> (Kers) writes:
> >if I cast (say) (int (*)( void *, void *)) strcmp, and pass it to (say) qsort
> >(as the compar parameter), can I expect it to work, and does such usage

> Actually, the answers FOR THIS PARTICULAR CASE are `yes' and `yes'.

> 	int (*)(void *, void *)		[qsort compare function]
> and	int (*)(char *, char *)		[strcmp]

If you want to sort an array of strings, e.g.
	char *myarray[N_Of_Strings];
	...
	qsort(myarray, N_Of_Strings, sizeof myarray[0], {{SOMETHING}})
**don't** try to pass 'strcmp' as the fourth argument of qsort().  The
comparison function is not given the elements of the array, but
``POINTERS to the elements being compared''.  What you need is

    int strptrcmp(char **s1, char **s2)
	{ return strcmp(*s1, *s2); }

and pass that as the fourth argument.  I can't think of any case where it
would make sense to pass strcmp to qsort().

Did you know that C.A.R.Hoare pointed out in 1962 that Quicksort does
1.4 times as many comparisons as [the number done by merge sort]?
He should know: he invented it.



More information about the Comp.lang.c mailing list