To sort the array, use qsort()
and pass a comparison function.
Here is one that produces the correct result for all possible values of the price
member:
typedef struct profile {
char gender[1];
double soc;
int price;
...
} PROFILE;
int compare_price(const void *a, const void *b) {
const PROFILE *oa = a;
const PROFILE *ob = b;
return (oa->price > ob->price) - (oa->price < ob->price);
}
int compare_soc(const void *a, const void *b) {
const PROFILE *oa = a;
const PROFILE *ob = b;
return (oa->soc > ob->soc) - (oa->soc < ob->soc);
}
Notes:
the simple subtraction of values produces incorrect results if the difference does not fit in the int
type. For example -2
and INT_MAX
cannot be correctly compared with the subtraction method. It would not work for floating point values either.
the above method can be used for all comparable types, including double
except for NaN
.
If you wish to handle NaN
, here is how to group them at the end:
#include <math.h>
int compare_soc_nan_at_the_end(const void *a, const void *b) {
const PROFILE *oa = a;
const PROFILE *ob = b;
if (isnan(oa->soc)) {
return isnan(ob->soc) ? 0 : 1;
} else
if (isnan(ob->soc)) {
return -1;
} else {
return (oa->soc > ob->soc) - (oa->soc < ob->soc);
}
}
double
seems like a rather nonsensical type for a social security number. It should likely bechar [10]
(if you want to allow entry of not-strictly-numeric values) oruint32_t
. – Verdieverdigrisdouble
may not be ideal, but it's perfectly adequate for holding a 9-digit integer value. At least you won't run into the problem of rounded fractional representations. – Gwindouble
isn't the best choice. It's not incorrect code though - there are no bugs that will result from that design choice, as long as the format of Social Security numbers does not change. I thought it was necessary to provide some balance. – Gwindouble
simply won't work. You still seem to be saying that, and I'd like to know your rationale. The only lurking bug I've been able to imagine is losing the leading zeros. – Gwin