title: Sorting Array of Struct Pointers
body: <p>I am trying to sort array of structs using <code>qsort()</code> but frustratingly, it's not working. I have read the manpage for <code>qsort()</code> and I think I have the comparator function that syntactically looks okay, but when I print the "sorted" array after calling <code>qsort()</code>, nothing is sorted in my array.</p>
  
  <p>The code:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  #define ARRAY_SZ 5
  
  typedef struct SingleChar
  {
      unsigned char Character;
      unsigned int Weight;
  } *SingleCharPtr;
  
  int CompareWeights(const void *a, const void *b)
  {
      const SingleCharPtr p1 = (SingleCharPtr)a;
      const SingleCharPtr p2 = (SingleCharPtr)b;
  
      // printf("Weight1: %u\tWeight2: %u\n", p1-&gt;Weight, p2-&gt;Weight);
      // return (p1-&gt;Weight - p2-&gt;Weight);
  
      if (p1-&gt;Weight &lt; p2-&gt;Weight)
          return -1;
      else if (p1-&gt;Weight &gt; p2-&gt;Weight)
          return 1;
      else
          return 0;
  }
  
  
  SingleCharPtr MakeChar(unsigned char c, unsigned int w)
  {
      SingleCharPtr scptr = malloc(sizeof(struct SingleChar));
  
      if (!scptr)
      {
          fprintf(stderr, "[Error] Out of memory\n");
          exit(1);
      }
  
      scptr-&gt;Character = c;
      scptr-&gt;Weight = w;
  
      return scptr;
  }
  
  int main(void)
  {
      SingleCharPtr *chars = malloc(ARRAY_SZ * sizeof(SingleCharPtr));
  
      chars[0] = MakeChar('B', 3);
      chars[1] = MakeChar('E', 7);
      chars[2] = MakeChar('A', 4);
      chars[3] = MakeChar('D', 6);
      chars[4] = MakeChar('C', 2);
  
      qsort(chars, ARRAY_SZ, sizeof(SingleCharPtr), &amp;CompareWeights);
  
      int i;
      for (i = 0; i &lt; ARRAY_SZ; i++)
      {
          printf("Character: %c\tWeight: %u\n", chars[i]-&gt;Character, chars[i]-&gt;Weight);
          free(chars[i]);
      }
  
      free(chars);
  
      return 0;
  }
  </code></pre>
  
  <p>Also, in the comparator function (<code>CompareWeights()</code>), I found out that when I print the weight of the structs pointed by <code>SingleCharPtr</code>, I get 0s for all of them.</p>
  
  <p>Any pointer to right direction would be highly appreciated. </p>