title: Sorting an array of structs with qsort
body: <p>I'm writing a program that sorts a &quot;bigram array.&quot; Basically, I have an array that contains BigramObjects. Each object contains a &quot;count&quot; and &quot;bigram.&quot; I want to sort my bigram array in order of &quot;count.&quot; Below is the code I've attempted to use to solve this.</p>
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;assert.h&gt;
  #include &lt;stdio.h&gt;
  
  #include &quot;bigramArray.h&quot;
  
  typedef struct bigramObject *BigramObject; 
  
  struct bigramObject {
      char *bigram;
      int count;
  };
  
  struct bigramArray {
      BigramObject *data;
      int size;
  };
  
  #define NUMBER_OF_CHARACTERS (256)
  
  BigramArray bigramArrayCreate(void) {
      BigramArray b = malloc(sizeof(struct bigramArray));
      assert(b);
  
      b-&gt;size = NUMBER_OF_CHARACTERS * NUMBER_OF_CHARACTERS;
      b-&gt;data = malloc(sizeof(struct bigramObject) * NUMBER_OF_CHARACTERS * NUMBER_OF_CHARACTERS);
      assert(b-&gt;data);
      
      for(int i = 0; i &lt; NUMBER_OF_CHARACTERS; i++) {
          for(int j = 0; j &lt; NUMBER_OF_CHARACTERS; j++) {
              BigramObject obj = malloc(sizeof(struct bigramObject));
              assert(obj);
              
              //Store the bigram for this cell
              obj-&gt;bigram = malloc(sizeof(char) * 2);
              assert(obj-&gt;bigram);
  
              obj-&gt;bigram[0] = i;
              obj-&gt;bigram[1] = j;
              obj-&gt;count = 0;
              
              b-&gt;data[i * NUMBER_OF_CHARACTERS + j] = obj;
              
          }
      }
      return b;
  }
  
  void bigramArrayDestroy(BigramArray b) {
      for(int i = 0; i &lt; NUMBER_OF_CHARACTERS; i++) {
          for(int j = 0; j &lt; NUMBER_OF_CHARACTERS; j++) {
              free(b-&gt;data[i * NUMBER_OF_CHARACTERS + j]-&gt;bigram);
              free(b-&gt;data[i * NUMBER_OF_CHARACTERS + j]);
          }
      }
      
      free(b-&gt;data);
      free(b);
  }
  
  int compare(const void *a, const void *b) {
  
      const BigramObject objA = (BigramObject) a;
      const BigramObject objB = (BigramObject) b;
      
      return objA-&gt;count - objB-&gt;count;
  }
  
  void sortBigramArray(BigramArray b) {
      // UP TO HERE IS GOOD
      qsort(b-&gt;data, b-&gt;size, sizeof(BigramObject), compare);
  }
  </code></pre>
  <p>However, when I test the sort, the program doesn't sort anything at all. I've ran gdb on a completely vanilla bigram array (basically all the counts are 0), and I noticed that objA and objB both do not have counts of 0 (they are closer to numbers like 4215872 and have differences of multiples of two after I stepped through a few). In the sortBigramArray function all the counts were still 0. Could someone explain to me why this change is occurring?</p>