我正在尝试按字段“名称”对结构进行排序,但是它不起作用:/ 您能告诉我或解释我没有看到的问题吗?
struct clients {
int id;
char name[27];
};
int comparator(const void* p, const void* q){
return strcmp(((struct list_node*)p)->name,
((struct list_node*)q)->name);
}
void sort_by_name(struct list_node *node){
const int length = count_list(node);
struct list_node *arr[length];
int i=0;
while (node)
{
arr[i]=node;
node = node->next;
i++;
}
printf("Before sort:\n");
for (i = 0; i < length; i++) {
printf("Id = %d, Name = %s\n",
arr[i]->id, arr[i]->name);
}
qsort(arr, length, sizeof(struct list_node), comparator);
printf("After sort:\n");
for (i = 0; i < length; i++) {
printf("Id = %d, Name = %s\n",
arr[i]->id, arr[i]->name);
}
}
结果:
Before sort:
Id = 11, Name = adam
Id = 20, Name = mati
Id = 25, Name = zenek
Id = 28, Name = mat
Process finished with exit code -1073741819 (0xC0000005).
我使用主菜单中的功能-用户必须确定打印排序还是不排序列表
答案 0 :(得分:0)
您的问题是:
qsort(arr, length, sizeof(struct list_node), comparator);
您告诉qsort
数组具有列表节点,但是数组只有 pointers 可以列出节点,所以:
qsort(arr, length, sizeof(struct list_node *), comparator);