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