Let's suppose we have a structure:
struct product
{
char name[30];
float price;
};
I want to sort it using qsort first by price, and if the prices are equal, by name. How I thought of writing the compare function:
int compare(const void *a, const void *b )
{
int comp = a.price - b.price;
if (comp < 0 )
return 1
if (comp > 0 )
return 0;
comp = strcmp(a.name, b.name);
if ( comp < 0 )
return 1;
else
if ( comp > 0 )
return 0;
}
Since I have only used the usual compare function for qsort, I don't know how to go about this. I think that I'm accessing the fields incorrectly, based on the errors given, so could you please point out my mistakes writing the compare function?
qsort, usestd::sortinstead (and usestd::string). If you're using C, please edit your question and check other examples of qsort usage. Also turn on your compiler warnings to the max once you've fixed the type problems.