Reputation: 68
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 *));
Upvotes: 1
Views: 479
Reputation: 133849
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.
Upvotes: 2