6

ソートしたいもの(構造体へのポインタの配列)は比較しているもの(文字列)ではないため、これがqsortで可能かどうかはわかりません。

これは私のプログラムの要約版です (qsort() を呼び出す前にすべての学生データがコアにあり、n がソートするレコードの数であると仮定します):

struct student {
        char lname[NAMESIZE + 1];
        char fname[NAMESIZE + 1];
        short mid;
        short final;
        short hmwks;
};

int cmp(const void *, const void *);

int
main(int argc, char **argv)
{
        int n;
        struct student *data[MAX];

        qsort(data, n, sizeof(struct student *), cmp);

        return 0;
}

int
cmp(const void *p0, const void *p1)
{
        return strcmp((*(struct student *) p0).lname,
                      (*(struct student *) p1).lname);
}
4

3 に答える 3

5

に渡されるのcmp()struct student**パラメータです ( を装ってvoid*)。したがってcmp()、次のように変更します。

int
cmp(const void *p0, const void *p1)
{
        struct student* ps0 = *(struct student**) p0;
        struct student* ps1 = *(struct student**) p1;

        return strcmp( ps0->lname, ps1->lname);
}
于 2012-05-04T05:38:39.523 に答える
3

次のようになります。

int
cmp(const void *p0, const void *p1)
{
        // pn is a pointer to an element of the array,
        // so, it's effectively a pointer to a pointer to a struct.
        // Therefore, we need to cast it appropriately to struct student **.
        // To get a pointer to a struct from it, we dereference it once,
        // hence the "*". Then we need to extract a pointer to the beginning
        // of a string, hence the "->".
        return strcmp((*(struct student **) p0)->lname,
                      (*(struct student **) p1)->lname);
}
于 2012-05-04T05:37:09.917 に答える