home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung 2 / Power-Programmierung CD 2 (Tewi)(1994).iso / c / library / dos / diverses / tctnt / qs.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-27  |  1.5 KB  |  60 lines

  1. /* QS.C: sorting arrays of structures
  2.  
  3.         The following code demonstrates how to use qsort() to sort an
  4.         array of structures. After entering this small program, step
  5.         through it with the IDE debugger, placing a watch on the
  6.         variables in sort_function() to better understand what is
  7.         happening.
  8. */
  9.  
  10. #include <stdio.h>                // for printf()
  11. #include <stdlib.h>                // for qsort()
  12. #include <string.h>                // for strcmp()
  13. #include <dos.h>                    // for MK_FP()
  14.  
  15. int sort_function( const void *a, const void *b);
  16.  
  17. struct foo {
  18.         char *c;
  19.         int xx;
  20. };
  21.  
  22. struct foo *list[4];
  23. struct foo a1 = {"cat",3 };
  24. struct foo a2 = {"cab",3};
  25. struct foo a3 = {"cap",2 };
  26. struct foo a4 = {"cal",1 };
  27.  
  28. //*******************************************************************
  29. int main(void)
  30. {
  31.   int  x;
  32.   list[0]=&a1;
  33.     list[1]=&a2;
  34.   list[2]=&a3;
  35.   list[3]=&a4;
  36.  
  37.     qsort((void *)list, 4, sizeof(list[0]), sort_function);
  38.   for (x = 0; x < 4; x++)
  39.         printf("%s\n", list[x]->c);
  40.   return 0;
  41. } // end of main()
  42.  
  43. /*-------------------------------------------------------------------
  44.     sort_function -
  45. */
  46.  
  47. int sort_function( const void *a, const void *b) {
  48.    unsigned int aa,bb; // Will be used for offset address
  49.    struct foo *ap,*bp;
  50.  
  51.      aa=*(unsigned*)a;  // a and b point to an address which in turn
  52.      bb=*(unsigned*)b;  // points to the offset address of the struct
  53.  
  54.      // Make a far pointer to struct address
  55.      ap=(struct foo*)MK_FP(_DS,aa);
  56.      bp=(struct foo*)MK_FP(_DS,bb);
  57.  
  58.      return( strcmp(ap->c,bp->c) );
  59. } // end of sort_function()
  60.