1

I'm trying to sort an array of pointers to structures where the key to compare is one of the structure's property.

I think that probably is the compare method.

Here's an example code.

#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;
}
0

1 Answer 1

9

I guess this should be simpler..

  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);
    }

And also I think the qsort function call could be definitely right if it were something like this,

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

I think the third argument must be the size of the structure and you can be definitely be sure if it were something like the above..

Sign up to request clarification or add additional context in comments.

3 Comments

struct BINARY_ARRAY_RECORD **records so records[0] its the same as struct BINARY_ARRAY_RECORD *
I thought it was ok the first answer but when i try with more than 2 pointers on the array fails. the correct answer is that gave me Ajai. I edit a little to get rid of the variables. int compare(const void *node1, const void *node2) { return strcmp( (*(struct BINARY_ARRAY_RECORD * const *) node1)->name, (*(struct BINARY_ARRAY_RECORD * const *) node2)->name ); }
why? the subscript operator dereferer from struct BINARY_ARRAY_RECORD ** to struct BINARY_ARRAY_RECORD *

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.