Need help using qsort with an array of structs

前端 未结 4 2009
忘掉有多难
忘掉有多难 2020-11-29 07:39

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;
         


        
4条回答
  •  一整个雨季
    2020-11-29 08:09

    Your Soc should almost certainly not be of type double, but anyway here's an example of what a compare function needs to return:

    int compare(const void *p1, const void *p2)
    {
        const struct profile *elem1 = p1;    
        const struct profile *elem2 = p2;
    
       if (elem1->soc < elem2->soc)
          return -1;
       else if (elem1->soc > elem2->soc)
          return 1;
       else
          return 0;
    }
    

    Thanks for pointing out the const void *.

    Here is a complete example (archived): Sorting Structures with the C qsort() Function

提交回复
热议问题