Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!olivea!mintaka!bloom-picayune.mit.edu!athena.mit.edu!jik From: jik@athena.mit.edu (Jonathan I. Kamens) Newsgroups: comp.unix.questions Subject: Re: qsort parameters Message-ID: <1991May9.165053.21224@athena.mit.edu> Date: 9 May 91 16:50:53 GMT References: <1991May9.042556.5565@csc.canberra.edu.au> Sender: news@athena.mit.edu (News system) Organization: Massachusetts Institute of Technology Lines: 53 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@Athena.MIT.EDU Allston, MA 02134 Office: 617-253-8085 Home: 617-782-0710 -- #include #include 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(); }