Sorting Structures

Joe Huffman joe at proto.com
Thu Jun 6 04:43:28 AEST 1991


nsfacgs at prism.gatech.EDU (Gary Smith) writes:

>Can someone explain why this sort will not work under BC++. Thanks.

>#include    <stdlib.h>
>
>int my_sort(struct personel *s, struct personel *d);
>[...stuff deleted...]
>    qsort(employee, 5, sizeof (struct personel), my_sort);

You mean it won't compile, right?  It does 'work' once you get it to compile.

The prototype for qsort() in <stdlib.h> has the comparision function being
(in essence):

	int qsort(void *,size_t,size_t,int (*)(const void *,cons void *).

You were passing to qsort a pointer to a function that did not match the
prototype.  Either change the define and prototype of my_sort() (bad name --
should be my_compare() or something similar) to match the qsort prototype.  
Or you can cast the pointer in the qsort call like this:

    qsort(employee, 5, sizeof (struct personel),
      (int (*)(const void *,const void *))my_sort);

The changeing of the prototype and definition of the function to match the
prototype of qsort() is the preferred method but is more work.  It will 
require a cast of the 'void *' arguments to 'struct personel *' arguments
(or assigning the void *'s to new pointers of the correct type).  

The casting of the function pointer in the call to qsort() is risky.  If you 
change the program to be C++ or do any of other things that change parameter 
passing, _near/_far function/code pointers, function returns, etc in some 
implementations.  You will end up with a obscure failure/crash when qsort() 
calls the comparision function.
-- 
joe at proto.com



More information about the Comp.lang.c mailing list