home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / MDASORT.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  99 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  MDASORT.C - Test program for mdalloc()/amalloc() demonstrating sorting
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <ctype.h>
  10. #include <limits.h>
  11. #include "snparray.h"
  12. #include "bc_rand.h"
  13.  
  14. int compare(const void *elem1, const void *elem2);
  15. int posn;
  16.  
  17. void usage(void)
  18. {
  19.       puts("Usage: MDATEST {A | M}");
  20.       puts("where: A means to use amalloc()");
  21.       puts("       M means to use mdalloc()");
  22.       exit(EXIT_FAILURE);
  23. }
  24.  
  25. main(int argc, char *argv[])
  26. {
  27.       int i, arg;
  28.       char **ary;
  29.  
  30.       if (argc < 2)
  31.             usage();
  32.       arg = toupper(*argv[1]);
  33.       if (arg != 'M' && arg != 'A')
  34.             usage();
  35.       printf("MDATEST: Using %s\n\n",
  36.              ('M' == arg) ? "mdalloc()" : "amalloc()");
  37.  
  38.       /*
  39.       **  Create a 5 x 40 array of char to hold 5 strings
  40.       */
  41.  
  42.       if ('M' == arg)
  43.       {
  44.             if (NULL == (ary = mdalloc(sizeof(char), 5, 40)))
  45.             {
  46.                   puts("mdalloc() failed");
  47.                   return EXIT_FAILURE;
  48.             }
  49.       }
  50.       else
  51.       {
  52.             if (NULL == (ary = amalloc(sizeof(char), NULL, 2, 5, 40)))
  53.             {
  54.                   puts("amalloc() failed");
  55.                   return EXIT_FAILURE;
  56.             }
  57.       }
  58.  
  59.       /*
  60.       **  Fill the array with recognizable random strings
  61.       */
  62.  
  63.       randomize();
  64.       for (i = 0; i < 5; ++i)
  65.       {
  66.             posn = sprintf(ary[i], "String #%d val = ", i + 1);
  67.             sprintf(ary[i] + posn, "%04X", random(UINT_MAX));
  68.       }
  69.  
  70.       /*
  71.       **  Display the unsorted array
  72.       */
  73.  
  74.       for (i = 0; i < 5; ++i)
  75.             printf("%d - %s\n", i, ary[i]);
  76.       puts("");
  77.  
  78.       /*
  79.       **  Sort the array and display it again
  80.       */
  81.  
  82.       qsort(ary, 5, sizeof(char *), compare);
  83.  
  84.       for (i = 0; i < 5; ++i)
  85.             printf("%d - %s\n", i, ary[i]);
  86.  
  87.       return EXIT_SUCCESS;
  88. }
  89.  
  90. int compare(const void *elem1, const void *elem2)
  91. {
  92.       char *e1 = *((char **)elem1), *e2 = *((char **)elem2);
  93.       long l1, l2;
  94.  
  95.       l1 = (unsigned)strtol(&e1[posn], NULL, 16);
  96.       l2 = (unsigned)strtol(&e2[posn], NULL, 16);
  97.       return (l2 < l1) ? 1 : ((l1 == l2) ? 0 : -1);
  98. }
  99.