Reputation: 7345
I did not find anything about this on the man page, but cppreference.com says:
The signature of the comparison function should be equivalent to the following:
int cmp(const void *a, const void *b);
The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array.
Would converting the strings with strtod, atof
etc. come under modification and result in undefined behavior or so?
The objective is to sort an array of char *
numerically. If it is illegal, do I have to write my own sort routine?
Upvotes: 1
Views: 96
Reputation: 144695
Converting the strings pointed to by the array elements using strtod
or atof
is perfectly fine because neither of these functions modify their argument strings. Note that the comparison function arguments of type const void *
do not point to the strings in your example, they point to individual char *
elements of the array, which it must not change. What these char *
pointers point to should not be changed either as this might affect the result of further comparisons involving the same string pointers, producing inconsistent results, hence causing undefined behavior in qsort
.
Here is an example:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int my_compare(const void *a, const void *b) {
char * const *sa = a;
char * const *sb = b;
double xa = strtod(sa, NULL);
double xb = strtod(sb, NULL);
return isnan(xa) ? (isnan(xb) ? 0 : 1) :
isnan(xb) ? -1 :
(xa > xb) - (xa < xb);
}
int main() {
char *array[] = { "1.0", "10.0", "2.0" };
size_t n = sizeof(array) / sizeof(array[0]);
qsort(array, n, sizeof array[0], my_compare);
for (size_t i = 0; i < n; i++)
printf("%s\n", array[i]);
return 0;
}
Upvotes: 2
Reputation: 59997
A function should only do what it says on the tin. In this case, it should only do a comparison.
To aid this, and to try to ensure that this is all that it does, it uses the keyword const
.
So if necessary just take local copies of the data. In most (all?) this is usually not necessary.
EDIT
As strtod
and atof
do not modify the strings, they can be used.
Upvotes: 2