The first qsort argument is a pointer to the beginning of the array to be sorted. Instead
qsort(i[5], 5, sizeof(double), sort);
he must read
qsort(i, 5, sizeof(double), sort);
Some additional observations:
- The length of the initializer
i is incorrect ( i has five elements, but the initializer has six). - Hard coding 5 into the
qsort call causes problems later. - The name "
i " is most often used for cycle counters, etc. - The call to the
sort comparison function is confusing. - The comparison function is incorrect. See how it will compare numbers
1.1 and 1.2 . Also think about what happens if the difference between the two values ββdoes not match int .
I would rewrite your entire example like this:
double arr[] = {1.023, 1.22, 1.56, 2, 5, 3.331}; int cmp(const void *x, const void *y) { double xx = *(double*)x, yy = *(double*)y; if (xx < yy) return -1; if (xx > yy) return 1; return 0; } int main() { qsort(arr, sizeof(arr)/sizeof(arr[0]), sizeof(arr[0]), cmp); }
Note that the comparison function above still does not handle NaN correctly; I leave this as an exercise so that the reader can fix it.
source share