开发者

Writing a comparision function for qsort

I'm writing a comparision function that compares and organizes names by ascending order of last name and if both last names are the same, descending order of first names. The function I have right now will not do that.

Here is the function:

int namecmp(const void *p, const void *q)
{
    const name *pp = p;
    const name *qq = q;
    int n;

    if((n = strcmp(pp->last, qq->last)) != 0)
        return n;

    return qq->first - pp->first;
}

I am trying to organize a dynamic array of structures, here are my structures.

typedef struct
{
char last[NAMESIZE];
char first[NAMESIZE];
}name;

typedef struct
{
int id;
name name;
float score;
}record;

typedef struct {
record *data; /* the dynamic array */
size_t nalloc; /* number of records allocated */
size_t nused; /* number of records in use */
} record_list;

and here is how qsort is called.

qsort(list->data, list->nused, sizeof(list->data[0]), namecmp);

Any help would be appreciated.

EDIT: I did what you suggested now i have the wrong output.

my output is:

3456789 Burns, Monty: 100.00
4567890 Simpson, Lisa: 95.00
1234567 Simpson, Homer: 35.50
6666666 Simpson, Bart: 45.00
2345678 Flanders, Ned: 9开发者_StackOverflow中文版9.50

EDIT 2:

How i store string into the structure.

            if(sscanf(line,"%s", lastname) == 1)
        {

            if(strlen(lastname) < NAMESIZE)
            {
                lastname[0] = toupper((int)lastname[0]);
                strcpy(rec->name.last, lastname);
                break;
            }
        }


You need to call strcmp on the first name as well or this will not work (as that's just subtracting addresses in memory). Change the last line to

return strcmp(pp->first, qq->first);


The comparison function has two comparisons (Edited one), but in different order. First has strcmp(p, q) and return statement has strcmp(q,p). Make them same, and it ll work !!

Shash

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜