qsort() - HELP
Gerhard Gucher
gegu at bii.UUCP
Wed Feb 14 02:10:12 AEST 1990
In article <5916 at ozdaltx.UUCP>, root at ozdaltx.UUCP (root) writes:
> After going over the manuals more times than I'd like, I still can't
> figure out how to get qsort() (S) to operate. The example shows
> something like:
>
> void qsort(base, nel, width, compar)
> char *base
> unsigned nel, width
> int (*compar)()
>
> Is base supposed to be an array?
> nel & width are self-explanitory
> What is compar() looking for or how is it assigned?
>
>
> The objective is to sort an array of strings in alpha order and then
> be able to read them. So far I'm getting is core dumps.
>
qsort is a little bit tricky for arrays of strings. compar() will
get the address of two items to be sorted as arguments. Since your
arguments are strings (char*'s) you must supply a compare function
which accepts (char**)'s as args.
The Example has been tested on a SUN OS 4.03 cc compiler.
Example:
#define NUM_ELEM(a) ( sizeof(a)/sizeof(a[0]) )
/* array to be sorted */
char * array[] = { "beta", "gamma", "alpha", "delta", "epsilon" };
extern int qsort();
/****************************************************************/
int ind_strcmp(s,t) /* indirect string compare for qsort */
char** s;
char** t;
{
return( strcmp(*s,*t) );
}
/****************************************************************/
/* ARGSUSED */
int
main(argc,argv)
int argc;
char *argv[];
{
int i;
(void) qsort( (char*)(&array[0]),
NUM_ELEM(array),
sizeof(array[0]),
ind_strcmp /* gets the address of the char ptrs */
);
/* print the sorted array */
for( i=0; i< NUM_ELEM(array); i++ )
(void)printf( "%s\n", array[i] );
} /* main() */
--
+------------------------------------------------------------------+
| Gerry Gucher uunet!bii!gegu gegu at bii.bruker.com |
| Bruker Instruments Inc. Manning Park Billerica MA 01821 |
+------------------------------------------------------------------+
More information about the Comp.lang.c
mailing list