如何解决使用 qsort 函数对结构进行排序
所以我需要使用 qsort() 对包含结构的数组进行排序
#include <stdio.h>
// =========
struct pair
{
int encounters;
};// pair{}
int compaireEncounters(const void*,const void*);
int main()
{
struct pair* working[5];
working[0]->encounters = 10;
working[1]->encounters = 3;
working[2]->encounters = 1;
qsort(working,5,sizeof(struct pair),compareEncounters);
int i = 0;
while (i < 3)
{
printf("%d \n",working[i]->encounters)
i++;
}
}
int compaireEncounters(const void* av,const void* bv)
{
int a = ((struct pair*)av)->encounters;
int b = ((struct pair*)bc)->encounters;
return(a > b);
}
我正在尝试获取输出:
1
3
10
但是我得到了一个分段错误核心转储。
这里有什么问题?
解决方法
在取消引用指针之前,您必须将指针分配给有效的缓冲区。
在这种情况下,working
应该是结构数组,而不是指针数组。
另外不要忘记初始化所有要排序的元素。
您的代码中还有更多错误:
-
qsort
的使用没有包含正确的标题 (stdlib.h
) - 在
compareEncounters
函数中使用了未声明的main
。 -
printf()
语句后缺少分号。 - 在
bc
函数中使用了未声明的compaireEncounters
。
固定代码:
#include <stdio.h>
#include <stdlib.h>
// =========
struct pair{
int encounters;
};// pair{}
int compaireEncounters(const void*,const void*);
int main() {
struct pair working[5];
working[0].encounters = 10;
working[1].encounters = 3;
working[2].encounters = 1;
working[3].encounters = 334;
working[4].encounters = 42;
qsort(working,5,sizeof(struct pair),compaireEncounters);
int i = 0;
while (i < 3) {
printf("%d \n",working[i].encounters);
i++;
}
}
int compaireEncounters(const void* av,const void* bv){
int a = ((struct pair*)av)->encounters;
int b = ((struct pair*)bv)->encounters;
return(a > b);
}
如果你想处理一个指针数组,
- 在取消引用之前分配缓冲区并分配它们。
- 修正
qsort()
的元素大小。 - 修正
compaireEncounters
以比较指向结构的指针。
#include <stdio.h>
#include <stdlib.h>
// =========
struct pair{
int encounters;
};// pair{}
int compaireEncounters(const void*,const void*);
int main() {
struct pair* working[5];
working[0] = malloc(sizeof(*working[0])); working[0]->encounters = 10;
working[1] = malloc(sizeof(*working[1])); working[1]->encounters = 3;
working[2] = malloc(sizeof(*working[2])); working[2]->encounters = 1;
working[3] = malloc(sizeof(*working[3])); working[3]->encounters = 334;
working[4] = malloc(sizeof(*working[4])); working[4]->encounters = 42;
qsort(working,sizeof(*working),working[i]->encounters);
i++;
}
}
int compaireEncounters(const void* av,const void* bv){
int a = (*(struct pair**)av)->encounters;
int b = (*(struct pair**)bv)->encounters;
return(a > b);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。