简体   繁体   English

对指向另一个结构内的结构的指针数组进行排序

[英]Sorting an array of pointers to struct inside another struct

I have two structs, the first one looks like this:我有两个结构,第一个看起来像这样:

typedef struct plant
{
  char ID[10];

  char scientific_name[MAX_NAME];

  char **alias;

  int n_alias;

  int n_seeds;

} plant;

and the second one is essentially an array of members第二个本质上是一组成员

typedef struct catalog
{
  plant **plants;

  long catalog_size;
 /*specifies if the plants array is either sorted by ID or scientific_name*/
  char ordering_method[5];

} catalog;

I was trying to use qsort to sort the **plants array inside catalog and my function call is as follows:我试图使用 qsort 对目录中的 **plants 数组进行排序,我的 function 调用如下:

int catalog_sort(catalog *c, const char *ordering_method)
{
    if (!strcasecmp(ordering_method, "ID"))
        qsort(c->plants, c->catalog_size, sizeof(plant *), qsortKey_ID);
    else if (!strcasecmp(ordering_method, "name"))
        qsort(c->plants, c->catalog_size, sizeof(plant *), qsortKey_name);
    else
        return -1;

    return 0;
}

Both qsortKey_ functions work basically the same but compare a different element of the struct两个 qsortKey_ 函数的工作原理基本相同,但比较结构的不同元素

int qsortKey_ID(const void *a, const void *b)
{
    const plant *pa = (plant *)a;
    const plant *pb = (plant *)b;

    /*checking to see if data is corrupted when the fuction gets called*/
    printf("ID A - %s, ID B - %s, COMP: %d\n", pa->ID, pb->ID, strcmp(pa->ID, pb->ID));

    return strcmp(pa->ID, pb->ID);
}

When i run this code, qsort does not work properly, failing to order the array and valgrind falgs "Invalid read size of 1" on both strcmp function calls made by either of the qsortKey_ functions, which is in line with the fact that the printed data by the prinf just above is indeed corrupted, funny enough the array itself is fine afterwards, just not properly sorted.当我运行此代码时,qsort 无法正常工作,无法在两个 qsortKey_ 函数进行的 strcmp function 调用上订购数组和 valgrind 错误“无效读取大小为 1”,这与打印的事实一致上面prinf的数据确实已损坏,有趣的是,数组本身之后很好,只是没有正确排序。

I've been struggling with this for some time now to no avail, so any input is appreciated.我已经为此苦苦挣扎了一段时间,但无济于事,因此感谢您的任何意见。 Is this not a correct application of qort?这不是qort的正确应用吗? Should i resort to implementing a sorting algorithm manually?我应该求助于手动实现排序算法吗?

You are missing one indirection.您缺少一种间接方式。

The comparison function takes two parameters that point at the array elements, thus:比较 function 采用两个指向数组元素的参数,因此:

int qsortKey_ID(const void *a, const void *b)
{
    const plant *pa = *(plant **)a; // a == &plants[some index]
    const plant *pb = *(plant **)b; // b == &plants[some other index]

    /*checking to see if data is corrupted when the fuction gets called*/
    printf("ID A - %s, ID B - %s, COMP: %d\n", pa->ID, pb->ID, strcmp(pa->ID, pb->ID));

    return strcmp(pa->ID, pb->ID);
}

Notice the additional asterisks.注意额外的星号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM