Need help using qsort with an array of structs

Julian Hernandez picture Julian Hernandez · May 24, 2011 · Viewed 69.5k times · Source

Now, I have seen various examples, but I don't get what they mean.

Here's my structure

typedef struct profile{
    char gender[1];
    double soc;
       . . .
} PROFILE;

where soc is social security number that I'm going to be sorting by.

I know you need a compare function, but I don't know how to come up with the exact thing I need.

Answer

koko.auth picture koko.auth · Jan 13, 2013

Here is an example of using qsort for an array of structs in C

/* qsort example */
#include <stdio.h>
#include <stdlib.h>

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

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

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

  return ( orderB->price - orderA->price );
}

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

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

hope it helps

katerina dimitris

(all regards to pitsi)