【问题标题】:sort array of pointers to structures qsort对指向结构的指针数组进行排序 qsort
【发布时间】:2011-12-10 04:09:49
【问题描述】:

我正在尝试对指向结构的指针数组进行排序,其中要比较的键是结构的属性之一。

我认为这可能是比较方法。

这是一个示例代码。

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

struct BINARY_ARRAY_RECORD {
    char *name;
};

int compare(const void *node1, const void *node2) {
    return strcmp(
        ((struct BINARY_ARRAY_RECORD *) node1)->name,
        ((struct BINARY_ARRAY_RECORD *) node2)->name
    );
}

int main()
{
    struct BINARY_ARRAY_RECORD **records;

    records = malloc(sizeof(struct BINARY_ARRAY_RECORD *) * 2);

    records[0] = malloc(sizeof(struct BINARY_ARRAY_RECORD));
    records[1] = malloc(sizeof(struct BINARY_ARRAY_RECORD));

    records[0]->name = malloc(sizeof(char) * (strlen("string2") + 1));
    records[1]->name = malloc(sizeof(char) * (strlen("string1") + 1));

    strcpy(records[0]->name, "string2");
    strcpy(records[1]->name, "string1");

    qsort(records, 2, sizeof(records[0]), compare);

    printf("%s\n", records[0]->name);
    printf("%s\n", records[1]->name);

    return 0;
}

【问题讨论】:

    标签: c pointers qsort


    【解决方案1】:

    我想这应该更简单..

      int compare(const void *node1, const void *node2) {
          BINARY_ARRAY_RECORD *ptr1 = *(BINARY_ARRAY_RECORD * const *)node1;
          BINARY_ARRAY_RECORD *ptr2 = *(BINARY_ARRAY_RECORD * const *)node2;
          return strcmp(ptr1->name, ptr2->name);
        }
    

    而且我认为如果是这样的话,qsort 函数调用肯定是正确的,

    qsort(records, 2, sizeof(BINARY_ARRAY_RECORD*), compare);
    

    我认为第三个参数必须是结构的大小,您可以确定它是否像上面的那样..

    【讨论】:

    • struct BINARY_ARRAY_RECORD **records 所以 records[0] 和 struct BINARY_ARRAY_RECORD *
    • 我认为第一个答案没问题,但是当我尝试在数组上使用超过 2 个指针时失败。正确的答案是给了我Ajai。我进行了一些编辑以摆脱变量。 int compare(const void *node1, const void *node2) { return strcmp( (*(struct BINARY_ARRAY_RECORD * const *) node1)->name, (*(struct BINARY_ARRAY_RECORD * const *) node2)->name ); }
    • 为什么?下标运算符从 struct BINARY_ARRAY_RECORD ** 到 struct BINARY_ARRAY_RECORD *
    猜你喜欢
    • 2015-12-13
    • 2014-07-04
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2020-11-09
    • 1970-01-01
    相关资源
    最近更新 更多