qsort
passes pointers to the elements of the list to the comparison routine as it sorts. Since your list is already a list of pointers-to-Queue
, pointers to those are pointers-to-pointers-to-Queue
.
Qsort not working the way I expect it to with void pointers
-
31-07-2022 - |
Domanda
So I am trying to use qsort to sort a generic array list of void pointers in C.
When I actually use the array list I am storing Queue
pointers.
I am pretty sure I am calling qsort
correctly
qsort(al->list, al->size, sizeof(void *), al->cf );
In my comparator function, I want to do this
int compareQCtgry(const void * queueA, const void * queueB)
{
Queue * q1 = (Queue *) queueA;
Queue * q2 = (Queue *) queueB;
return strcmp(q1->category, q2->category);
}
However, I get a segfault.
But when I change it to
int compareQCtgry(const void * queueA, const void * queueB)
{
Queue * q1 = *(Queue **) queueA;
Queue * q2 = *(Queue **) queueB;
return strcmp(q1->category, q2->category);
}
It works, yet it makes no sense to me. Why cast the void pointer to a Queue **
and then dereference it when it seems like you should just be able to cast it with Queue *
?
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow