HOW does "qsort" handle different variable type?

Doug Gwyn gwyn at smoke.brl.mil
Mon Mar 25 18:02:05 AEST 1991


In article <1991Mar23.063112.22168 at minyos.xx.rmit.oz.au> rcoahk at chudich.co.rmit.oz (Alvaro Hui Kau) writes:
>	I am interested in HOW the system routine
>	handle different variable types..
>	Furthermore, WHY char casting is used for
>	the base pointer?

I think your question boils down to, "Explain the function of the first
argument to the qsort() function."

qsort()'s first argument is a "generic" pointer, formerly of type char*,
in ANSI C of type void*.  The reason for this is of course that the
implementation of qsort() has no way of knowing what the actual data
type will be at run time.  The third argument to qsort() specifies the
byte-width of a single element in the array of whatever actual type is
being sorted, so that qsort() is able to construct generic pointers to
the proper elements that it passes to the user-supplied comparison
function.  qsort() manages the sorting algorithm, while the user-
supplied comparison function gives meaning to comparison of whatever
data types are actually being sorted.  Note that the comparison function
has generic-pointer types for its arguments, which must be converted to
pointers to the actual data types being compared.



More information about the Comp.lang.c mailing list