使用qsort()对struct指针数组进行排序

时间:2015-06-25 02:24:29

标签: c pointers struct

我需要根据struct中存储的值对包含struct指针的数组进行排序。代码是:

typedef unsigned int word;
typedef struct xid { word w[5]; } xid;
typedef xid *list;

int comparexid(xid *id1, xid *id2);
static int quicksort(list *base, size_t narray, size_t size, int(*compare)(const void *, const void *));


int main(int argc, char *argv[])
{
    static list addr[MAXENTRIES];
    int nlist;

    // Fill addr
    quicksort((list *)&addr[0], nlist, sizeof(list), comparexid);
}

int comparexid(xid *id1, xid *id2)
{
    int cmp;
    cmp = memcmp(id1, id2, 20);

    if (cmp > 0)
            return 1;
    else if (cmp < 0)
            return -1;
    else
            return 0;
}

static int quicksort(list *base, size_t narray, size_t size, int (*compare)(const void *, const void *))
{
    // Print original
    qsort(&base[0], narray, size, compare);
    // Print sorted
}

structs指向的addr未正确排序。

9个structs的样本输入(打印在16中),输出如下:

输入:

b23456789ab23456789ab23456789ab234567898
b23456789ab23456789ab23456789ab234567897
b23456789ab23456789ab23456789ab234567896
b23456789ab23456789ab23456789ab234567895
b23456789ab23456789ab23456789ab234567894
b23456789ab23456789ab23456789ab234567893
b23456789ab23456789ab23456789ab234567892
b23456789ab23456789ab23456789ab234567891
b23456789ab23456789ab23456789ab234567890

输出:

b23456789ab23456789ab23456789ab234567892
b23456789ab23456789ab23456789ab234567891
b23456789ab23456789ab23456789ab234567898
b23456789ab23456789ab23456789ab234567890
b23456789ab23456789ab23456789ab234567897
b23456789ab23456789ab23456789ab234567896
b23456789ab23456789ab23456789ab234567895
b23456789ab23456789ab23456789ab234567894
b23456789ab23456789ab23456789ab234567893

0 个答案:

没有答案