使用qsort()对包含字符串的结构的指针进行排序

Der*_*rek 5 c pointers qsort

我不确定这是否可以与qsort一起使用,因为我要排序的内容(指向结构的指针数组)不是我要比较的内容(字符串)。

这是我程序的简化版本(假设所有学生数据在调用qsort()之前都处于核心位置,而n是要排序的记录数):

struct student {
        char lname[NAMESIZE + 1];
        char fname[NAMESIZE + 1];
        short mid;
        short final;
        short hmwks;
};

int cmp(const void *, const void *);

int
main(int argc, char **argv)
{
        int n;
        struct student *data[MAX];

        qsort(data, n, sizeof(struct student *), cmp);

        return 0;
}

int
cmp(const void *p0, const void *p1)
{
        return strcmp((*(struct student *) p0).lname,
                      (*(struct student *) p1).lname);
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*urr 5

什么将被传递到cmp()struct student**参数(在假借void*)。因此更改cmp()如下:

int
cmp(const void *p0, const void *p1)
{
        struct student* ps0 = *(struct student**) p0;
        struct student* ps1 = *(struct student**) p1;

        return strcmp( ps0->lname, ps1->lname);
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*nze 3

它应该是这样的:

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);
}
Run Code Online (Sandbox Code Playgroud)