title: Using qsort() to sort array of struct pointers
body: <p>I need to sort an array consisting of <code>struct</code> pointers based on the values stored in the <code>struct</code>. The code is:</p>
  
  <pre><code>typedef unsigned int word;
  typedef struct xid { word w[5]; } xid;
  typedef xid *list;
  
  int comparexid(xid *id1, xid *id2);
  static int quicksort(list *base, size_t narray, size_t size, int(*compare)(const void *, const void *));
  
  
  int main(int argc, char *argv[])
  {
      static list addr[MAXENTRIES];
      int nlist;
  
      // Fill addr
      quicksort((list *)&amp;addr[0], nlist, sizeof(list), comparexid);
  }
  
  int comparexid(xid *id1, xid *id2)
  {
      int cmp;
      cmp = memcmp(id1, id2, 20);
  
      if (cmp &gt; 0)
              return 1;
      else if (cmp &lt; 0)
              return -1;
      else
              return 0;
  }
  
  static int quicksort(list *base, size_t narray, size_t size, int (*compare)(const void *, const void *))
  {
      // Print original
      qsort(&amp;base[0], narray, size, compare);
      // Print sorted
  }
  </code></pre>
  
  <p>The <code>structs</code> that are pointed to by <code>addr</code> are not sorted correctly.</p>
  
  <p>The sample input (printed in base 16) of 9 such <code>structs</code> and the output are as follows:</p>
  
  <p>Input:</p>
  
  <pre><code>b23456789ab23456789ab23456789ab234567898
  b23456789ab23456789ab23456789ab234567897
  b23456789ab23456789ab23456789ab234567896
  b23456789ab23456789ab23456789ab234567895
  b23456789ab23456789ab23456789ab234567894
  b23456789ab23456789ab23456789ab234567893
  b23456789ab23456789ab23456789ab234567892
  b23456789ab23456789ab23456789ab234567891
  b23456789ab23456789ab23456789ab234567890
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>b23456789ab23456789ab23456789ab234567892
  b23456789ab23456789ab23456789ab234567891
  b23456789ab23456789ab23456789ab234567898
  b23456789ab23456789ab23456789ab234567890
  b23456789ab23456789ab23456789ab234567897
  b23456789ab23456789ab23456789ab234567896
  b23456789ab23456789ab23456789ab234567895
  b23456789ab23456789ab23456789ab234567894
  b23456789ab23456789ab23456789ab234567893
  </code></pre>