home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!sun-barr!olivea!spool.mu.edu!darwin.sura.net!jhunix.hcf.jhu.edu!blaze.cs.jhu.edu!rhombus!wilson
- From: wilson@rhombus.cs.jhu.edu (Dwight Wilson)
- Newsgroups: comp.lang.c
- Subject: Re: Problems with QSORT and function prototypes
- Message-ID: <1992Sep15.123225.22760@blaze.cs.jhu.edu>
- Date: 15 Sep 92 12:32:25 GMT
- References: <1992Sep15.043445.3519@midway.uchicago.edu>
- Sender: news@blaze.cs.jhu.edu (Usenet news system)
- Organization: The Johns Hopkins University CS Department
- Lines: 43
-
- In article <1992Sep15.043445.3519@midway.uchicago.edu> pynq@midway.uchicago.edu writes:
- >I have not been able to figure out how to pass a function pointer to the
- >QSORT intrinsic function, when using function prototypes.
- >
- >Here is my program:
- >
- >#include <stdio.h>
- >#include <stdlib.h>
- >
- >struct thing {
- > char *text;
- > int textlen;
- > } *things;
- >
- >my_cmp(struct thing *t1, struct thing *t2)
- >{
- > /* Key is in col 39, length 12 */
- > return strncmp(t1 -> text + 38,t2 -> text + 38,12);
- >}
- >
- >int_cmp(int *p1, int *p2) { return (*p1 - *p2); }
- >
- >main()
- >{
- > /* (You get same results with either my_cmp or int_cmp) */
- > qsort(things,5,sizeof(struct thing),my_cmp);
- >
- >}
-
- qsort() is declared as:
-
- void qsort(void *base, size_t nmemb, size_t size,
- int (*compar)(const void *, const void *));
-
- Your problem is being caused by the fourth argument, the comparison
- function. qsort's declaration means that the comparison function
- should take two (void *) parameters and return an int.
-
- Your functions expect two struct thing pointers or two int pointers.
- You must rewrite them to take (void *) arguments (and cast them
- internally).
-
- -Dwight
-