using qsort() to sort pointers to structs containing strings

前端 未结 3 1261
Happy的楠姐
Happy的楠姐 2021-01-13 02:58

I\'m not sure if this is possible to do with qsort because what I want to sort (array of pointers to struct) is not what I am comparing (strings).

Here is an abridge

3条回答
  •  旧时难觅i
    2021-01-13 03:26

    It should be something like this:

    int
    cmp(const void *p0, const void *p1)
    {
            // pn is a pointer to an element of the array,
            // so, it's effectively a pointer to a pointer to a struct.
            // Therefore, we need to cast it appropriately to struct student **.
            // To get a pointer to a struct from it, we dereference it once,
            // hence the "*". Then we need to extract a pointer to the beginning
            // of a string, hence the "->".
            return strcmp((*(struct student **) p0)->lname,
                          (*(struct student **) p1)->lname);
    }
    

提交回复
热议问题