home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / c / 20132 < prev    next >
Encoding:
Text File  |  1993-01-24  |  2.0 KB  |  56 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
  3. From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
  4. Subject: Re: Use of ANSI qsort
  5. Message-ID: <9302414.18593@mulga.cs.mu.OZ.AU>
  6. Keywords: qsort
  7. Sender: news@cs.mu.OZ.AU
  8. Organization: Computer Science, University of Melbourne, Australia
  9. References: <C0pBDG.7Ky@news2.cis.umn.edu> <1993Jan12.024932.27939@organpipe.uug.arizona.edu> <C19KrI.M9A@compsci.liverpool.ac.uk>
  10. Date: Sun, 24 Jan 1993 03:57:46 GMT
  11. Lines: 43
  12.  
  13. scst81@csc.liv.ac.uk (Mr. I. Rowland) writes:
  14.  
  15. >I am using the ANSI function qsort to sort an array of structs.
  16. [...]
  17. >qsort((char *) clast_record,
  18. >        (unsigned) num_records, 
  19. >        sizeof(struct clast_item),lithology_compare);
  20. >}
  21.  
  22. qsort is prototyped as
  23.     void qsort(void *, size_t, size_t,
  24.            int (*) (const void *, const void *));
  25.  
  26. There is no need to cast 'clast_record' to (char *).
  27. 'num_records' should probably be cast to (size_t) rather than (unsigned),
  28. if it does indeed need to be case, but it is perhaps better to declare
  29. 'num_records' to be of type size_t in the first place.
  30.  
  31. >The lithology_compare function is as follows :
  32. >
  33. >int lithology_compare (struct clast_item *a, struct clast_item *b) {
  34. >    return strcmp(a->lithology,b->lithology);
  35. >}
  36.  
  37. The prototype for lithology_compare() must be exactly the same as given in
  38. the prototype for the fourth argument of qsort(). i.e.
  39.  
  40.     int lithology_compare (const void *x, const void *y);
  41.  
  42. In the function you then need to cast the (const void *) pointers to the
  43. correct type before using them. For example,
  44.  
  45.     int lithology_compare (const void *x, const void *y) {
  46.         struct clast_item *a = (struct clast_item *) x;
  47.         struct clast_item *b = (struct clast_item *) y;
  48.         return strcmp(a->lithology,b->lithology);
  49.     }
  50.  
  51. -- 
  52. Fergus Henderson             fjh@munta.cs.mu.OZ.AU      
  53. This .signature virus is a self-referential statement that is true - but 
  54. you will only be able to consistently believe it if you copy it to your own
  55. .signature file!
  56.