0

I'm trying to use the c-lib function qsort() to sort an array of longs. I do it as follows:

int
compar(long *e1, long *e2)   // for decreasing order
{
   if (*e1 > *e2) return -1;
   if (*e1 < *e2) return 1;
   return 0;
}

void
c_lib_quick_sort(long *a, long n)
{
   qsort(a, n, sizeof(long), compar);
}

The code works perfectly, but clang produces the following warning

sort_timings.c:262:30: warning: incompatible function pointer types passing 'int (long *, long *)' to parameter of type 'int (* _Nonnull)(const void *, const vo
id *)' [-Wincompatible-function-pointer-types]
   qsort(a, n, sizeof(long), compar);
                             ^~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/stdlib.h:161:22: note: passing argument to parameter '__compar' here
            int (* _Nonnull __compar)(const void *, const void *));

Can someone show me how to eliminate the warning? The warning refers to things like (* _Nonnull), which I've never seen before.

I wrote similar code 15 years ago, but gcc at the time did not produce any warnings. The newer compilers are more strict about types.

  • Try declaring the parameters of `compar` as `const void *` and then casting them to `const long *` inside. – Ion Larrañaga Apr 10 '21 at 16:04
  • See [Confused about Qsort and Pointers](https://stackoverflow.com/questions/19670320/confused-about-qsort-and-pointers). – mkayaalp Apr 10 '21 at 16:04
  • The `_Nonnull` is a hint to the compiler that the pointer is not supposed to be the null pointer, so it can give better optimizations and warnings. You can ignore that part. – Nate Eldredge Apr 10 '21 at 16:09

1 Answers1

2

The warning indicates what is the expected function signature

passing argument to parameter '__compar' here
            int (* _Nonnull __compar)(const void *, const void *));

So changing it accordingly, should help address the warnings:

int
compar(const void *p1, const void *p2)   // for decreasing order
{
    const long* e1 = (const long*)p1;
    const long* e2 = (const long*)p2;
    if (*e1 > *e2) return -1;
    if (*e1 < *e2) return 1;
    return 0;
}
Zoso
  • 3,273
  • 1
  • 16
  • 27