c - 为 qsort 编写比较函数

标签 c structure qsort

我正在编写一个比较函数,它按姓氏的升序比较和组织名字,如果两个姓氏相同,则按名字的降序排列。我现在拥有的功能不会那样做。

函数如下:

int namecmp(const void *p, const void *q)
{
    const name *pp = p;
    const name *qq = q;
    int n;

    if((n = strcmp(pp->last, qq->last)) != 0)
        return n;

    return qq->first - pp->first;
}

我正在尝试组织一个动态的结构数组,这是我的结构。

typedef struct
{
char last[NAMESIZE];
char first[NAMESIZE];
}name;

typedef struct
{
int id;
name name;
float score;
}record;

typedef struct {
record *data; /* the dynamic array */
size_t nalloc; /* number of records allocated */
size_t nused; /* number of records in use */
} record_list;

这里是 qsort 的调用方式。

qsort(list->data, list->nused, sizeof(list->data[0]), namecmp);

如有任何帮助,我们将不胜感激。

编辑:我按照你的建议做了,现在我得到了错误的输出。

我的输出是:

3456789 Burns, Monty: 100.00
4567890 Simpson, Lisa: 95.00
1234567 Simpson, Homer: 35.50
6666666 Simpson, Bart: 45.00
2345678 Flanders, Ned: 99.50

编辑 2:

我如何将字符串存储到结构中。

            if(sscanf(line,"%s", lastname) == 1)
        {

            if(strlen(lastname) < NAMESIZE)
            {
                lastname[0] = toupper((int)lastname[0]);
                strcpy(rec->name.last, lastname);
                break;
            }
        }

最佳答案

您还需要对名字调用 strcmp,否则这将不起作用(因为这只是减去内存中的地址)。将最后一行改为

return strcmp(pp->first, qq->first);

关于c - 为 qsort 编写比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6886708/

相关文章:

c++ - 快速排序后我的数据库的最终值损坏

c - ImageMagick 中使用的算法

c++ - char 变量是否总是表示为取消引用的 char*[2] 和 {'x' ,\0}?

mysql - tt_content 中图像的 TYPO3 数据库关系

c - 结构中存在的 realloc int 指针 [C]

c - struct 中这个 `data[0]` 声明的目的是什么?

c++ - 将 qsort 与 std::sort 进行比较

c - 如何合并N个文件

c - 正在创建文件,但未将数据推送到文件中

c - 在c中排序5d数组