"incompatible function pointer types" in C

405 Views Asked by At

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]
1

There are 1 best solutions below

5
Tom Karzes On

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