1

I want to use qsort function but I'm getting an error. Can anyone tell me how to fix the code?

int cmp_arv(struct train *t1,
            struct train *t2)
{
    return (t1->arv - t2->arv);
}

void prepare_data(void)
{
    int i;

    for (i = 0; i < nconn; i++){
        rtrains[i].from = trains[i].to;
        rtrains[i].to = trains[i].from;
        rtrains[i].dpt = BIAS- trains[i].arv;
        rtrains[i].arv = BIAS- trains[i].dpt;
        rtrains[i].fare = trains[i].fare;
    }
    qsort (trains, nconn,sizeof(struct train), cmp_arv);
    qsort (rtrains, nconn, sizeof(struct train), cmp_arv);
}

The error message looks like:

incompatible function pointer types passing 'int (struct train *, struct train *)'
to parameter of type 'int (* _Nonnull)(const void *, const void *)' [-Wincompatible-function-pointer-types]
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
mann
  • 19
  • 3
  • 5
    The arguments to the compare function must be `const void *`. The code should convert to `const struct train *` inside the function. – user3386109 Jul 26 '23 at 02:18
  • @user3386109: that should be an answer, not a comment. Answers-posing-as-comments are about as useful as comments-posing-as-answers, i.e., not very :-) – paxdiablo Jul 26 '23 at 02:43
  • 2
    @paxdiablo This is a duplicate 100 times over. But finding a good duplicate is not always as easy as it should be. And as discussed many times on meta, there's no reward for putting in extra effort. So I post the comment, then go looking ... – user3386109 Jul 26 '23 at 02:58
  • @user3386109, I just find it funny that making a comment is less effort than finding the dupe, given the assistance fron SO. To be honest, if I was sure it was a dupe, I probably wouldn't even waste the effort of a comment :-) But I understand your point, it is a good one. – paxdiablo Jul 26 '23 at 04:44
  • Hi. When feedback in comments on a question of yours makes you realise the answer/solution, then please do not delete the question; especially not without any (grateful...) comment to the person who helped you. Instead please create your own answer, which you can even accept yourself. @mann – Yunnosch Jul 26 '23 at 12:24

1 Answers1

2

The comparison function that's passed to qsort has a fixed type, which therefore can't depend on any user-defined data types. To use your own types, you need to cast the pointer types inside the function, so that the required prototype is maintained. In your case, you want the following:

int cmp_arv(const void *t1_arg,
            const void *t2_arg)
{
    const struct train *t1 = t1_arg;
    const struct train *t2 = t2_arg;

    return t1->arv - t2->arv;
}
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41