3 ms·
from TFA >>> compare is a function which returns an integer less than, equal to, or greater than zero if the first argument is less than, equal to, or greater
by _ZeD_ 4y ago
from TFA
>>> compare is a function which returns an integer less than, equal to, or greater than zero if the first argument is less than, equal to, or greater than the second. Because it is a C function, it takes in void pointers which we must convert back to actual values. One safe way to achieve such a conversion is through the memcpy function.
wait, what?
why do you need to copy the memory??? can't you just cast to (double*) and deference???
- cryo 4y agoMaybe due alignment, on ARM unaligned dereference would crash if I remember correctly. So it's safe to copy the value first and use that aligned memory for the comparison.
- strager 4y agoThat would imply that the input array given to qsort was misaligned. I don't think alignment is an issue in the comparator.
- scaredginger 4y agoYeah, I'm pretty sure you're right, the author might just be cargo culting here
- gpderetta 4y agoIt might be an hypercorrection. memcpy is a safe way to do type punning, but no punning is necessary here as the pointee was originally a double so the cast back and dereference should be perfectly safe. edit s/pointer/pointee
- cochne 4y agoYep, this works just fine: int compare(const void *a, const void *b) { return *(double*)a - *(double*)b; }