I'm trying to sort struct by field 'name', but It don't works :/ Can you show or explain me the problem that i didn't see?
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);
}
}
Result:
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).
I use the function in main menu - user have to decide print sorted or not sorted list
Your problem is:
qsort(arr, length, sizeof(struct list_node), comparator);
You tell qsort
the array has list nodes, but the array has only pointers to list nodes, so:
qsort(arr, length, sizeof(struct list_node *), comparator);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.