1

我目前正在尝试使用 C 提供的内置快速排序来对指向结构的指针数组进行排序。我想根据结构中的名称元素对每个元素进行排序。

虽然我每次通过比较函数对整个数组的调试输出都显示该函数确实在移动元素,但最终结果不是正确的排序顺序。有什么我在这里看不到的吗?

typedef struct // The custom data type.
{
    char *name;
} Person;

----------------------------

Person **people; // A dynamically allocated array of Person pointers.
int numPeople;   // The logical index of people.
int maxPeople;   // The current maximum capacity of people.

int compare(const void *a, const void *b) // The comparison function for determining
{                                         //    alphabetic ordering.
   const Person *const *p1 = a;
   const Person *const *p2 = b;
   return strcmp((*p1)->name, (*p2)->name); // Compare alphabetically, return result.
}

void SomeFunction(void)
{
    qsort(people, numPeople, sizeof(Person *), compare); // Perform the sort.
}

感谢您对此的帮助。

4

2 回答 2

1

我已经测试了你的代码,它看起来工作正常。这是我用 gcc 4.5.2 编译的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct // The custom data type.
{
        char *name;
} Person;

Person **people; // A dynamically allocated array of Person pointers.
int numPeople;   // The logical index of people.
int maxPeople;   // The current maximum capacity of people.

int compare(const void *a, const void *b) // The comparison function for determining
{                                         //    alphabetic ordering.
        const Person *const *p1 = a;
        const Person *const *p2 = b;
        return strcmp((*p1)->name, (*p2)->name); // Compare alphabetically, return result.
}

void SomeFunction(void)
{
        qsort(people, numPeople, sizeof(Person *), compare); // Perform the sort.
}

int main()
{
        int iCnt;

        maxPeople = 4;
        numPeople = 4;

        people = calloc(1, sizeof(Person *) * maxPeople);

        people[0] = calloc(1, sizeof(Person));
        people[1] = calloc(1, sizeof(Person));
        people[2] = calloc(1, sizeof(Person));
        people[3] = calloc(1, sizeof(Person));

        people[0]->name = strdup("Tanya");
        people[1]->name = strdup("Alfred");
        people[2]->name = strdup("Harry");
        people[3]->name = strdup("Oakley");

        for(iCnt = 0; iCnt < numPeople; iCnt ++)
                printf("[%d] %s\n", iCnt, people[iCnt]->name);

        SomeFunction();

        for(iCnt = 0; iCnt < numPeople; iCnt ++)
                printf("[%d] %s\n", iCnt, people[iCnt]->name);

        return 0;
}

代码看起来合法,我不确定出了什么问题。您可以尝试编译我测试的代码并查看它是否有效?

于 2012-11-28T01:49:01.387 回答
0

你能试试这个吗

int compare(const void *a, const void *b) // The comparison function for determining
{                                         //    alphabetic ordering.
   const Person *p1 = *(const Person**)a;
   const Person *p2 = *(const Person**)b;
   return strcmp((p1)->name, (p2)->name); // Compare alphabetically, return result.
}
于 2012-11-28T01:29:18.580 回答