title: Qsort Comparison Function
body: <p>I am a beginner to C and I am trying to understand the comparison function needed for the qsort function.</p>
  
  <h2>Part One: Syntax</h2>
  
  <p>A simple suggested use is this (I have included some main() code to print the results as well):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int values[] = { 40, 10, 100, 90, 20, 25, 12, 13, 10, 40 };
  
  int compare(const void *a, const void *b)
  {
      const int *ia = (const int *)a; // casting pointer types 
      const int *ib = (const int *)b;
      return *ia  - *ib; 
  }
  
  int main()
  {
      int n;
      for (n=0; n&lt;10; n++)
      {
          printf("%d ",values[n]);
      }
      printf("\n");
      qsort(values, 10, sizeof(int), compare);
      for (n=0; n&lt;10; n++)
      {
          printf("%d ",values[n]);
      }
      printf("\n");
      system("pause");
      return 0;
  }
  </code></pre>
  
  <p>I don't understand why you need all the extra things in the compare function so I simplified it to this:</p>
  
  <pre><code>int compare (int *a, int *b)
      {
          return *a-*b; 
      }
  </code></pre>
  
  <p>This still works, and produces the same results. Can anyone explain to me what I removed, and why it still works?</p>
  
  <h2>Part Two: Why Pointers?</h2>
  
  <p>Additionally, do I really need to use pointers? Why can't I just compare "a" and "b" directly like so (this does NOT work):</p>
  
  <pre><code>int compare (int a, int b)
          {
              return a-b; 
          }
  </code></pre>
  
  <p>For some reason, with a multidimensional array, I was able to get away with NOT using pointers and for some reason it worked! What is going on? (Example code of sorting a multidimensional array by the 2nd item in each sub array):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int values[7][3] = { {40,55}, {10,52}, {100,8}, {90,90}, {20,91}, {25,24} };
  
  int compare(int a[2], int b[2])
  {
      return a[1] - b[1];
  }
  
  int main()
  {
      int n;
      for (n=0; n&lt;6; n++)
      {
          printf("%d,",values[n][0]);
          printf("%d ",values[n][1]);
      }
      printf("\n");
      qsort(values, 6, sizeof(int)*3, compare);
      for (n=0; n&lt;6; n++)
      {
          printf("%d,",values[n][0]);
          printf("%d ",values[n][1]);
      }
      printf("\n");
      system("pause");
      return 0;
  }
  </code></pre>
  
  <p>I am really glad the multidimensional array sorting is working as that is my <strong>end goal</strong> anyway, but I have no idea how I managed to get it to work (other than dumb luck and chopping up the code) so I would really love some explanation as to why some of the examples I provided work, and why some don't!</p>