1

I want to dynamic declare the function pointer and sort it

#include <stdio.h>
#include <stdlib.h>

int values[] = { 88, 56, 100, 2, 25 };


int main () {
   int n;

   printf("Before sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

   int (^comp)() = ^int(const void *a, const void *b) {
      return ( *(int*)a - *(int*)b );
   };


   qsort(values, 5, sizeof(int), /*ERROR*/comp);

   printf("\nAfter sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {   
      printf("%d ", values[n]);
   }

   return(0);
}

But I am getting Error below:

error: passing 'int (^)()' to parameter of incompatible type 'int (* _Nonnull)(const void *, const void *)' qsort(values, 5, sizeof(int), /ERROR/comp);

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

6
  • Well the compiler messages are clear enough. Commented Dec 17, 2017 at 5:28
  • Yeah, I don't know how Apple is doing these ^block things did it but I'd guess the type is not compatible. You don't need a closure here though Commented Dec 17, 2017 at 5:28
  • I think the question you should be asking is: "can I convert a block to a function pointer here?" Commented Dec 17, 2017 at 5:31
  • And the answer to my question would be "Not really" Commented Dec 17, 2017 at 5:32
  • Nvm, I found an answer to your question Commented Dec 17, 2017 at 5:42

1 Answer 1

2

Well, a block isn't a function pointer, and you can't really even wrap a block into a function pointer, so you might as well give up with that. Instead use the function qsort_b which is meant to be used with a block.

int (^comp)() = ^int(const void *a, const void *b) { return ( (int)a - (int)b ); };

qsort_b(values, 5, sizeof(int), comp);


But then, here you don't even need a closure, so you can use an ordinary function and a pointer to it:

int int_comp(const void *a, const void *b) {
    return ( *(int*)a - *(int*)b );
}

You can have several comparator functions to choose from, just assign the desired comparator to a function pointer variable:

int (* comp)(const void *a, const void *b);
... 
comp = int_comp;

However if you need to have some state within the actual comparison routine, naturally this doesn't work well.

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

Comments

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.