Question 13.9

Now I'm trying to sort an array of structures with qsort. My comparison function takes pointers to structures, but the compiler complains that the function is of the wrong type for qsort. How can I cast the function pointer to shut off the warning?


The conversions must be in the comparison function, which must be declared as accepting ``generic pointers'' (const void *) as discussed in question 13.8 above. The comparison function might look like

int mystructcmp(const void *p1, const void *p2)
{
	const struct mystruct *sp1 = p1;
	const struct mystruct *sp2 = p2;
	/* now compare sp1->whatever and sp2-> ... */
(The conversions from generic pointers to struct mystruct pointers happen in the initializations sp1 = p1 and sp2 = p2; the compiler performs the conversions implicitly since p1 and p2 are void pointers. Explicit casts, and char * pointers, would be required under a pre-ANSI compiler. See also question 7.7.)

If, on the other hand, you're sorting pointers to structures, you'll need indirection, as in question 13.8: sp1 = *(struct mystruct **)p1 .

In general, it is a bad idea to insert casts just to ``shut the compiler up.'' Compiler warnings are usually trying to tell you something, and unless you really know what you're doing, you ignore or muzzle them at your peril. See also question 4.9.

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