title: Why qsort from stdlib doesnt work with double values? [C]
body: <p>I wrote a simple program to sort out my array. The problem is that the code works with int values only while I need my array to have <code>double</code> elements ... Any help?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  double values[] = { 88, 56, 100, 2, 25 };
  
  int cmpfunc (const void * a, const void * b)
  {
      return ( *(int*)a - *(int*)b );
  }
  
  int main()
  {
      int n;
  
      printf("Before sorting the list is: \n");
      for( n = 0 ; n &lt; 5; n++ )
      {
          printf("%.2f ", values[n]);
      }
  
      printf("\n\n");
  
      qsort(values, 5, sizeof(double), cmpfunc);
  
      printf("\nAfter sorting the list is: \n");
      for( n = 0 ; n &lt; 5; n++ )
      {
          printf("%.2f ", values[n]);
      }
  
      printf("\n\n");
  
      return(0);
  }
  </code></pre>
  
  <p><strong>WORKING CODE:</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;math.h&gt;
  
  double values[] = { 88, 56, 100, 2, 25 };
  
  int compare (const void * a, const void * b)
  {
      if (*(double*)a &gt; *(double*)b) return 1;
      else if (*(double*)a &lt; *(double*)b) return -1;
      else return 0;
  }
  
  int main()
  {
      int n;
  
      printf("Before sorting the list is: \n");
      for( n = 0 ; n &lt; 5; n++ )
      {
          printf("%.2f ", values[n]);
      }
  
      printf("\n\n");
  
      qsort(values, 5, sizeof(double), compare);
  
      printf("\nAfter sorting the list is: \n");
      for( n = 0 ; n &lt; 5; n++ )
      {
          printf("%.2f ", values[n]);
      }
  
      printf("\n\n");
  
      return(0);
  }
  </code></pre>