home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / c / 13678 < prev    next >
Encoding:
Internet Message Format  |  1992-09-15  |  1.6 KB

  1. Path: sparky!uunet!sun-barr!olivea!spool.mu.edu!darwin.sura.net!jhunix.hcf.jhu.edu!blaze.cs.jhu.edu!rhombus!wilson
  2. From: wilson@rhombus.cs.jhu.edu (Dwight Wilson)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Problems with QSORT and function prototypes
  5. Message-ID: <1992Sep15.123225.22760@blaze.cs.jhu.edu>
  6. Date: 15 Sep 92 12:32:25 GMT
  7. References: <1992Sep15.043445.3519@midway.uchicago.edu>
  8. Sender: news@blaze.cs.jhu.edu (Usenet news system)
  9. Organization: The Johns Hopkins University CS Department
  10. Lines: 43
  11.  
  12. In article <1992Sep15.043445.3519@midway.uchicago.edu> pynq@midway.uchicago.edu writes:
  13. >I have not been able to figure out how to pass a function pointer to the
  14. >QSORT intrinsic function, when using function prototypes.
  15. >
  16. >Here is my program:
  17. >
  18. >#include <stdio.h>
  19. >#include <stdlib.h>
  20. >
  21. >struct thing {
  22. >        char *text;
  23. >        int textlen;
  24. >        } *things;
  25. >
  26. >my_cmp(struct thing *t1, struct thing *t2)
  27. >{
  28. >        /* Key is in col 39, length 12 */
  29. >        return strncmp(t1 -> text + 38,t2 -> text + 38,12);
  30. >}
  31. >
  32. >int_cmp(int *p1, int *p2) { return (*p1 - *p2); }
  33. >
  34. >main()
  35. >{
  36. >    /* (You get same results with either my_cmp or int_cmp) */
  37. >        qsort(things,5,sizeof(struct thing),my_cmp);
  38. >
  39. >}
  40.  
  41. qsort() is declared as:
  42.  
  43. void qsort(void *base, size_t nmemb, size_t size,
  44.            int (*compar)(const void *, const void *));
  45.  
  46. Your problem is being caused by the fourth argument, the comparison
  47. function.  qsort's declaration means that the comparison function
  48. should take two (void *) parameters and return an int.
  49.  
  50. Your functions expect two struct thing pointers or two int pointers.
  51. You must rewrite them to take (void *) arguments (and cast them
  52. internally).
  53.  
  54. -Dwight
  55.