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);
}
}
doubleseems 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.doublemay 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.