title: Sorting structure with C qsort()
body: <p>Having trouble getting my head around implementing the qsort() built into C to sort an array of structs by a stored int value (hitCount).</p>
  
  <p>My struct:</p>
  
  <pre><code>typedef struct words {
      const char *word;
      int hitCount;
  } words;
  </code></pre>
  
  <p>I'm trying to use the example given by Microsoft (<a href="http://support.microsoft.com/kb/73853" rel="nofollow">http://support.microsoft.com/kb/73853</a>).</p>
  
  <p>So I've got at the top:</p>
  
  <pre><code>typedef int (*compfn)(const void*, const void*);
  </code></pre>
  
  <p>and the comparision method:</p>
  
  <pre><code>int compare (words *a, words *b) {
      if (a-&gt;hitCount &gt; b-&gt;hitCount) {
          return -1;
      } else if (a-&gt;hitCount &lt; b-&gt;hitCount) {
          return 1;
      } else {
          return 0;
      }
  }
  </code></pre>
  
  <p>then within another method I call qsort with my array name and other details replacing the Microsoft example:</p>
  
  <pre><code>qsort((void *) &amp;output, outputLength, sizeof(words), (compfn)compare);
  </code></pre>
  
  <p>This gives a segmentation fault.</p>
  
  <p>I don't fully understand how to use qsort so I assume where I've adapted it from Microsoft's example I've done it incorrectly.</p>
  
  <p>I hope I've included the mistake and can get some enlightenment as to what I should be doing in order for this to work correctly.</p>
  
  <p>Many Thanks!</p>