HOW does "qsort" handle different variable type?

Blair P. Houghton bhoughto at nevin.intel.com
Sun Mar 24 12:34:19 AEST 1991


In article <1991Mar23.063112.22168 at minyos.xx.rmit.oz.au> rcoahk at chudich.co.rmit.oz (Alvaro Hui Kau) writes:
>Hi,
>	Furthermore, WHY char casting is used for
>	the base pointer?

Even in ANSI C, you can expect a pointer to char to be a pointer
to a byte.  This makes it a natural choice for a generic pointer
type.  It means that when the pointer is incremented by 1, the
location it points to will be one byte further in the memory.

Notice that you have to give also the number of bytes that
each object occupies.  qsort() uses that number to increment
the pointer and thus point to the next object, not just
the next byte.

In ANSI C, however, there's a special type, `void *', which
is designed specifically to be a generic pointer type, to
be used in exactly this way.

qsort()'s sorting algorithm often isn't the best [*] (the
algorithm you use should depend on the distribution and
organization of your data, so it's easy to define a class
of sets that make a given sorting algorithm thrash and
slog), but this usage of anonymous data methods is a
classic of modular programming.

				--Blair
				  "Waxing didactic this week..."

[*] the algorithm it uses can be different from library
to library:  anything from bubble-sort to hashing.



More information about the Comp.lang.c mailing list