views:

45

answers:

1

Ive got a task in C to sort a struct by using qsort

struct user {
    enum SEX{m, f} sex;
    char name[32];
    char phonenr[32];

};
typedef struct user User;

the users will be stored in a array of 25 elements

but how do i sort them on something like name ?

+6  A: 

In this case it's pretty easy, since strcmp works nicely with qsort. Try:

int compareUser(const void *v1, const void *v2)
{
    const User *u1 = v1;
    const User *u2 = v2;
    return strcmp(u1->name, u2->name);
}

Then use it like this:

qsort(array, 25, sizeof(User), compareUser);

Good luck!

Carl Norum
Edited to shut up warnings, being strictly correct is always a good idea.
Carl Norum