【问题标题】:Getting incompatible pointer type errors when using blocks with qsort in Clang在 Clang 中使用带有 qsort 的块时出现不兼容的指针类型错误
【发布时间】:2018-05-30 20:26:09
【问题描述】:

我要动态声明函数指针并排序

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

【问题讨论】:

  • 嗯,编译器的信息已经很清楚了。
  • 是的,我不知道 Apple 是如何做到这些 ^block 的,但我猜该类型不兼容。不过这里不需要关闭
  • 我认为您应该问的问题是:“我可以在这里将块转换为函数指针吗?”
  • 我的问题的答案是“Not really”
  • Nvm,我找到了你问题的答案

标签: c macos clang


【解决方案1】:

好吧,块不是函数指针,你不能really even wrap a block into a function pointer,所以你还不如放弃它。请改用函数qsort_b,该函数旨在与块一起使用。

int (^comp)() = ^int(const void *a, const void *b) { 返回 ( (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;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多