I’m qsort()ing some memory pointers in a list to allow a bsearch of them later in a function. My question is, do I need to type cast those values to something other than const void * to do a legal comparison in C? I could just do the conversion and let the compiler tell me, but I have a feeling that this might be compiler dependent.
Share
Comparisons are fine, arithmetic and dereferencing are not (because you don’t know the size of the underlying data). So yes, you can compare void pointers quite well (a).
However, keep in mind that you don’t usually compare the pointers passed to a
qsortcomparison function, unless you want to sort on their addresses. But, since they’ll be sorted in that order already (being an array), there’s not much of a use case for that 🙂You generally cast the void pointers to a specific pointer and then compare what they point to. Something like:
You don’t have to create temporaries like
str1andstr2(even though any decent compiler would optimise them out anyway). Other than a slight readability issue, there’s nothing wrong with:(a) Subject to the normal rules that the pointers must both point to elements of the same array or one beyond that array – anything else is undefined. I mention that for completeness but, if you’re using
qsort, you’ll be working on an array anyway.