How to use qsort() in an array structure in C language : <p>I am trying to use qsort() to sort the price in a structure. After the sorting, one of the element (test) in the structure becomes 0. Can you tell me why and how to solve it?</p>

<p>Thanks!</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

typedef struct {
    int price;
    int test;
    int id;
} order;
order list[10];
int i = 0;

int compare (const void * a, const void * b)
{

  order *orderA = (order *)a;
  order *orderB = (order *)b;

  return ( orderA-&gt;price - orderB-&gt;price );
}

int main ()
{
    srand ( time(NULL) );

    printf("Before sorting\n");
    for(i=0; i&lt;10; i++){ 
        list[i].price = rand()%10;
        list[i].test = rand()%10;
        list[i].id = i; 
        printf ("Order id = %d Price = %d Test = %d\n",list[i].id, list[i].price, list[i].test);           
    }
    printf("AFTER sorting\n");
    int n;
    qsort (list, 6, sizeof(order), compare);
    for (n=0; n&lt;10; n++)
         printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[i].test);          
    return 0;
}
</code></pre>

<p>The output are:</p>

<blockquote>
  <p>Before sorting<br>
  Order id = 0 Price = 4 Test = 2<br>
  Order id = 1 Price = 9 Test = 3<br>
  Order id = 2 Price = 5 Test = 0<br>
  Order id = 3 Price = 2 Test = 8<br>
  Order id = 4 Price = 8 Test = 5<br>
  Order id = 5 Price = 7 Test = 4<br>
  Order id = 6 Price = 9 Test = 3<br>
  Order id = 7 Price = 1 Test = 1<br>
  Order id = 8 Price = 8 Test = 4<br>
  Order id = 9 Price = 3 Test = 3<br>
  AFTER sorting<br>
  Order id = 3 Price = 2 Test = 0<br>
  Order id = 0 Price = 4 Test = 0<br>
  Order id = 2 Price = 5 Test = 0<br>
  Order id = 5 Price = 7 Test = 0<br>
  Order id = 4 Price = 8 Test = 0<br>
  Order id = 1 Price = 9 Test = 0<br>
  Order id = 6 Price = 9 Test = 0<br>
  Order id = 7 Price = 1 Test = 0<br>
  Order id = 8 Price = 8 Test = 0<br>
  Order id = 9 Price = 3 Test = 0</p>
</blockquote>
