所以我需要使用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, 5, sizeof(*working), 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);
}