home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
- From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
- Subject: Re: Use of ANSI qsort
- Message-ID: <9302414.18593@mulga.cs.mu.OZ.AU>
- Keywords: qsort
- Sender: news@cs.mu.OZ.AU
- Organization: Computer Science, University of Melbourne, Australia
- References: <C0pBDG.7Ky@news2.cis.umn.edu> <1993Jan12.024932.27939@organpipe.uug.arizona.edu> <C19KrI.M9A@compsci.liverpool.ac.uk>
- Date: Sun, 24 Jan 1993 03:57:46 GMT
- Lines: 43
-
- scst81@csc.liv.ac.uk (Mr. I. Rowland) writes:
-
- >I am using the ANSI function qsort to sort an array of structs.
- [...]
- >qsort((char *) clast_record,
- > (unsigned) num_records,
- > sizeof(struct clast_item),lithology_compare);
- >}
-
- qsort is prototyped as
- void qsort(void *, size_t, size_t,
- int (*) (const void *, const void *));
-
- There is no need to cast 'clast_record' to (char *).
- 'num_records' should probably be cast to (size_t) rather than (unsigned),
- if it does indeed need to be case, but it is perhaps better to declare
- 'num_records' to be of type size_t in the first place.
-
- >The lithology_compare function is as follows :
- >
- >int lithology_compare (struct clast_item *a, struct clast_item *b) {
- > return strcmp(a->lithology,b->lithology);
- >}
-
- The prototype for lithology_compare() must be exactly the same as given in
- the prototype for the fourth argument of qsort(). i.e.
-
- int lithology_compare (const void *x, const void *y);
-
- In the function you then need to cast the (const void *) pointers to the
- correct type before using them. For example,
-
- int lithology_compare (const void *x, const void *y) {
- struct clast_item *a = (struct clast_item *) x;
- struct clast_item *b = (struct clast_item *) y;
- return strcmp(a->lithology,b->lithology);
- }
-
- --
- Fergus Henderson fjh@munta.cs.mu.OZ.AU
- This .signature virus is a self-referential statement that is true - but
- you will only be able to consistently believe it if you copy it to your own
- .signature file!
-