user3706129
user3706129

Reputation: 229

Sorting array of structs

I have defined an array of structs

typedef struct sorting {
    int number
} SRT;

SRT *mystr = NULL;

which I later dynamically allocated. and I want to sort it by the number int;

What kind of function do I have to write in order for qsort to do it? I have written :

qsort(mystr,array_index,sizeof(mystr),magic);

int magic(const void *a, const void *b) {
    int one=((const struct mystr*)a)->number;
    int two(( const struct myst*)b)->number;

    return ( one-two);
}

but it didn't work. How can I do it? it throwed errors about not naming a type.

Upvotes: 0

Views: 120

Answers (2)

chqrlie
chqrlie

Reputation: 144770

You cannot reliably sort the array with the function as written:

  • It has syntax errors, some of which are typos, others indicate a confusion between types, struct tags and variable names.

  • return (one - two); only works for reasonably small values of one and two. It will invoke undefined behavior if there is an integer arithmetic overflow. For example, if one == INT_MAX and two == -1, the value of one - two is not specified by the C language and on common platform it is likely to return INT_MIN, a negative value, leading to incorrect sorting.

A simple solution is this:

int sort_function(const void *a, const void *b) {
    int one = ((const SRT*)a)->number;
    int two = ((const SRT*)b)->number;

    return (one > two) - (one < two);
}

The expression (one > two) - (one < two) evaluates to -1 if one is less than two, 0 if they are equal and 1 otherwise. In C, comparisons evaluate to 0 if false and 1 if true.

The sorting function should be used this way:

qsort(mystr, array_count, sizeof(*mystr), sort_function);
  • The second argument is the number of structures in the array pointed to by mystr.
  • The third argument is the size of a single structure: sizeof(mystr) is the size of the pointer, not the size of what is points to.
  • Avoid mysterious names like magic... use descriptive names for types, functions and variables.

Upvotes: 2

dbush
dbush

Reputation: 223972

Two problems:

qsort(mystr,array_index,sizeof(mystr),magic);

mystr is a pointer to SRT, so you're passing in the size of a pointer to the struct, not the size of the struct:

qsort(mystr,array_index,sizeof(STR),magic);

Then there's this:

int one=((const struct mystr*)a)->number;
int two(( const struct myst*)b)->number;

mystr is a variable name, not a type, and myst isn't defined anywhere. You need the type name here:

int one=((const SRT *)a)->number;
int two=((const SRT *)b)->number;

Upvotes: 0

Related Questions