Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

c - Need help using qsort with an array of structs

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

hope it helps

katerina dimitris

(all regards to pitsi)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...