简体   繁体   中英

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:

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

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.

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? 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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