使用qsort()对包含字符串的结构的指针进行排序 [英] using qsort() to sort pointers to structs containing strings

查看:250
本文介绍了使用qsort()对包含字符串的结构的指针进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

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

Here is an abridged version of my program (assume that all the student data is in core before we call qsort() and n is the number of records to sort):

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);
}

推荐答案

应该是这样的:

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);
}

这篇关于使用qsort()对包含字符串的结构的指针进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆