How to use qsort() in an array structure in C language

218 Views Asked by At

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?

Thanks!

#include <stdio.h>
#include <stdlib.h>

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->price - orderB->price );
}

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

    printf("Before sorting\n");
    for(i=0; i<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<10; n++)
         printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[i].test);          
    return 0;
}

The output are:

Before sorting
Order id = 0 Price = 4 Test = 2
Order id = 1 Price = 9 Test = 3
Order id = 2 Price = 5 Test = 0
Order id = 3 Price = 2 Test = 8
Order id = 4 Price = 8 Test = 5
Order id = 5 Price = 7 Test = 4
Order id = 6 Price = 9 Test = 3
Order id = 7 Price = 1 Test = 1
Order id = 8 Price = 8 Test = 4
Order id = 9 Price = 3 Test = 3
AFTER sorting
Order id = 3 Price = 2 Test = 0
Order id = 0 Price = 4 Test = 0
Order id = 2 Price = 5 Test = 0
Order id = 5 Price = 7 Test = 0
Order id = 4 Price = 8 Test = 0
Order id = 1 Price = 9 Test = 0
Order id = 6 Price = 9 Test = 0
Order id = 7 Price = 1 Test = 0
Order id = 8 Price = 8 Test = 0
Order id = 9 Price = 3 Test = 0

1

There are 1 best solutions below

0
On

After sorting, change

printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[i].test); 

to

printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[n].test);