I have got an array of the following structs:
typedef struct _my_data_
{
unsigned int id;
double latitude;
double longitude;
unsigned int content_len;
char* name_dyn;
char* descr_dyn;
} mydata;
and I would like to sort it ascending by the ID field. I read it is possible to sort arrays using the qsort function but I am not sure how to correctly use it when sorting structs.
You need a structure comparator function that matches the prototype of the function expected by
qsort(), viz:If you ever get to a more complex sort criterion, this is still a good basis because you can add secondary criteria using the same skeleton:
Clearly, this repeats for as many criteria as you need. If you need to call a function (
strcmp()?) to compare values, call it once but assign the return to a local variable and use that twice:Also, this template works when data members are unsigned integers, and it avoids overflow problems when comparing signed integers. Note that the short cut you might sometimes see, namely variations on:
is bad if
idis unsigned (the difference of two unsigned integers is never negative), and subject to overflow if the integers are signed and of large magnitude and opposite signs.