FletcherG FletcherG - 3 months ago 12
C Question

How to sort an array of structs using qsort()?

I have a struct :

struct data {
float goodbye;
char balance;
unsigned char clouds;
float badge;
double soda;
char bat;
short int parcel;
char vessel;
char spade;
long int cover;
unsigned long int hobbies;
short int voyage;
int stomach;
char sort;
char system [11];
unsigned short adjustment;
};


I need to create an array of structs and then be able to sort the various elements of the structs using the
qsort
function.

I've looked through other questions asked previously however none of them seem to work for my application.

I have tried something like the following:

static int cmpr(const void *a, const void *b) {
if (((data*)a)->goodbye < ((data*)b)->goodbye)
return 1;
else if (((data*)a)->goodbye > ((data*)b)->goodbye)
return -1;
else
return 0;
}


This isn't working for me either as I get
'data is undeclared in this function'

Answer

The type of your struct is struct data, not just data.

In C++ your code would work fine. In C, however, struct names require the struct keyword.

So, change your casts from (data*) to (struct data*).

Comments