home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_03_06 / 3n06052b < prev    next >
Text File  |  1992-04-16  |  2KB  |  78 lines

  1.  
  2. Listing 2
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. /*
  8.  * arraycmp - a general-purpose array comparer in C
  9.  * using run-time genericity
  10.  */
  11. typedef int (*cf_t)(const void *p, const void *q);
  12.  
  13. int arraycmp
  14.     (const void *a1, const void *a2, size_t n,
  15.     size_t size, cf_t cf)
  16.     {
  17.     const char *p1 = a1;
  18.     const char *p2 = a2;
  19.     size_t i;
  20.     int cmp;
  21.  
  22.     for (i = 0; i < n * size; i += size)
  23.         if ((cmp = cf(p1 + i, p2 + i)) != 0)
  24.             return cmp;
  25.     return 0;
  26.     }
  27.  
  28. /*
  29.  * Some element comparison functions
  30.  */
  31. int intcf(const void *p, const void *q)
  32.     {
  33.     return *(int *)p - *(int *)q;
  34.     }
  35.  
  36. int doublecf(const void *p, const void *q)
  37.     {
  38.     if (*(double *)p < *(double *)q)
  39.         return -1;
  40.     else if (*(double *)p == *(double *)q)
  41.         return 0;
  42.     else
  43.         return 1;
  44.     }
  45.  
  46. int strcf(const void *p, const void *q)
  47.     {
  48.     return strcmp(p, q);
  49.     }
  50.  
  51. /*
  52.  * Sample calls to arraycmp...
  53.  */
  54. int a[] = {1, 2, 3, 4, -5};
  55. int b[] = {1, 2, 3, 4, 4};
  56.  
  57. double f[] = {1, 2, 3, 4, 5};
  58. double g[] = {1, 2, 3, 3, 4};
  59.  
  60. char *s[] = {"123", "456", "789"};
  61. char *t[] = {"123", "789", "456"};
  62.  
  63. int main(void)
  64.     {
  65.     printf("a vs. b = %d\n",
  66.         arraycmp(a, b, 4, sizeof(int), intcf));
  67.     printf("a vs. b = %d\n",
  68.         arraycmp(a, b, 5, sizeof(int), intcf));
  69.     printf("f vs. g = %d\n",
  70.         arraycmp(f, g, 5, sizeof(double), doublecf));
  71.     printf("s vs. t = %d\n",
  72.         arraycmp(s, t, 3, sizeof(char *), strcf));
  73.     printf("s vs. t = %d\n",
  74.         arraycmp(s, t, 3, sizeof(char *), (cf_t)strcmp));
  75.     return 0;
  76.     }
  77.  
  78.