home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!munnari.oz.au!mel.dit.csiro.au!yarra!bohra.cpg.oz.au!daavid
- From: daavid@bohra.cpg.oz.au (Daavid Turnbull)
- Newsgroups: comp.lang.c
- Subject: Re: qsort problem....
- Message-ID: <1992Aug14.133320.28769@bohra.cpg.oz.au>
- Date: 14 Aug 92 13:33:20 GMT
- References: <1992Aug10.184635.11618@tin.monsanto.com>
- Organization: Computer Power Software
- Lines: 98
-
- In article <1992Aug10.184635.11618@tin.monsanto.com> bcschu@skws02.monsanto.com (Brett Schultz) writes:
- > Hello, for some reason I am having a problem with a qsort system call.
- >
- > Here is a test program similar to what I am trying to do:
- >
- > #include <stdio.h>
- > #include <stdlib.h>
- > typedef struct my_float {
- > float f;
- > }my_float;
-
- /*
- ** first add the correct prototype
- */
- int qs_compare(const void *a,const void *b)
- >
- >
- >
- > main()
- > {
- > my_float mf[5];
- > int i;
- >
- > mf[0].f = .5444;
- > mf[1].f = .345;
- > mf[2].f = .976;
- > mf[3].f = .764;
- > mf[4].f = .45345;
- >
- > for(i=0; i < 5; ++i)
- > printf("mf[%d] = %f\n",i,mf[i].f);
- >
- > printf("\n");
- >
- > /*qsort((void *) mf, 5, sizeof(my_float), qs_compare);*/
- >
- > for(i=0; i < 5; ++i)
- > printf("mf[%d].f = %f\n",i,mf[i].f);
- > }
- >
- /*
- ** Then make the function match the prototype (both qsort()'s and itself)
- */
- > int qs_compare(const void *a_,const void *b_)
- > {
- /*
- ** assign the passed args to variables of the correct type
- */
- myfloat *a = (myfloat) a_;
- myfloat *b = (myfloat) b_;
-
- > if (a->f < b->f)
- > return (-1);
- > else if (a->f == b->f)
- > return (0);
- > else
- > return (1);
- > }
- >
- > I want to sort an array of structures by a float in the structure.
- >
- > This is not compiling. Here are the errors:
- >
- [... unusually informative list of errors for this pretty common problem
- deleted...]
- >
- > Brett
- This at first feels like a clumbsy solution but you get passed that.
- The thing that pisses me off is that the most readable version of
- the solution, (IMHO the one I have presented) creates two extra variables,
- which are a complete waste of data.
-
- > I want to sort an array of structures by a float in the structure.
-
- A clever compiler might optimise this out.
-
- The other solution which is probably more efficient and is perfectly
- readable in this instance where the sort routine is short defines
- your sort function :
-
- int qs_compare(const void *a, const void *b)
- {
- if ((my_double *a)->f < (my_double *b)->f)
- return (-1);
- else if ((my_double *a)->f == (my_double *b)->f)
- return (0);
- else
- return (1);
- }
-
- Thats ansi for you,
-
- daavid
- --
- Daavid Turnbull
- daavid@bohra.cpg.oz +61 3 823 0222 (fax) +61 3 824 8068
- uunet!munnari!bohra.cpg.oz!daavid
- CP Software Export Pty Ltd ACN 006 640 133
-