在Clang中使用带qsort的块时出现不兼容的指针类型错误

问题描述 投票:1回答:1

我想动态声明函数指针并对其进行排序

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

但是我收到以下错误:

错误:将'int(^)()'传递给不兼容类型的参数'int(* _Nonnull)(const void *,const void *)'qsort(values,5,sizeof(int),/ ERROR / comp);

注意:将参数传递给参数'__compar'这里int(* _Nonnull __compar)(const void *,const void *));

c macos clang
1个回答
2
投票

好吧,一个块不是一个函数指针,你不能really even wrap a block into a function pointer,所以你不妨放弃它。而是使用与块一起使用的函数qsort_b

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

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


但是,在这里,您甚至不需要闭包,因此您可以使用普通函数和指向它的指针:

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

您可以选择多个比较器函数,只需将所需的比较器分配给函数指针变量:

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

但是,如果你需要在实际的比较例程中有一些状态,那么这自然不会很好。

© www.soinside.com 2019 - 2024. All rights reserved.