1
votes

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

1
Well the compiler messages are clear enough.user2736738
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 thoughAntti Haapala
I think the question you should be asking is: "can I convert a block to a function pointer here?"Antti Haapala
And the answer to my question would be "Not really"Antti Haapala
Nvm, I found an answer to your questionAntti Haapala

1 Answers

2
votes

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.