qsort parameters

Jonathan I. Kamens jik at athena.mit.edu
Fri May 10 02:50:53 AEST 1991


When you pass an array of strings into qsort, the width of each string in the
array does *not* vary according to its length.

Remember, literally, what char *filenames[] means.  It means an array of
pointers to char, not an array of strings.  And pointer to char, or char *,
type, is of a constant size.

Therefore, you would use:

	qsort((char *) filenames, num_names, sizeof(char *), cmp);

Note that the "cmp" function *cannot* be strcmp, since strcmp expects two char
*'s, and what it's actually going to get is to char **'s (read the man page
for qsort carefully -- it says that the comparison function gets two pointers
to elements of the array, and remember that the elements of the arrays are
char *'s).

The sample program appended to the end of this message illustrates all of this.

-- 
Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik at Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8085			      Home: 617-782-0710
-- 
#include <stdio.h>
#include <strings.h>

char *filenames[] = {
     "The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dogs."
};

print_names()
{
     int i;

     for (i = 0; i < sizeof(filenames) / sizeof(char *); i++)
	  printf("%s ", filenames[i]);
     printf("\n");
}

cmp(char **str1, char **str2)
{
     return(strcmp(*str1, *str2));
}

main()
{
     print_names();
     qsort((char *) filenames, sizeof(filenames) / sizeof(char *),
	   sizeof(char *), cmp);
     print_names();
}



More information about the Comp.unix.questions mailing list