Xref: utzoo comp.lang.c:25888 comp.unix.xenix:10062 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uunet!bii!gegu From: gegu@bii.UUCP (Gerhard Gucher) Newsgroups: comp.lang.c,comp.unix.xenix Subject: Re: qsort() - HELP Summary: qsort - HELP Message-ID: <275@bii.UUCP> Date: 13 Feb 90 15:10:12 GMT References: <5916@ozdaltx.UUCP> Followup-To: comp.lang.c comp.unix.xenix Organization: Bruker Instruments Inc., Billerica MA. Lines: 69 In article <5916@ozdaltx.UUCP>, root@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@bii.bruker.com | | Bruker Instruments Inc. Manning Park Billerica MA 01821 | +------------------------------------------------------------------+