how to sort array pointers of struct by name?

0

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

c
qsort
asked on Stack Overflow May 27, 2019 by Pluco • edited May 27, 2019 by Lundin

1 Answer

0

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);
answered on Stack Overflow May 27, 2019 by Paul Ogilvie

User contributions licensed under CC BY-SA 3.0