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 ?
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!
精彩评论