开发者

sort a struct array by attribute value

开发者 https://www.devze.com 2023-01-01 13:31 出处:网络
Ive got a task in C to sort a struct by using qsort struct user { enum SEX{m, f} sex; char name开发者_如何学编程[32];

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消