【问题标题】:error: invalid conversion from 'void*' to 'int (*)(const void*, const void*)'错误:从 'void*' 到 'int (*)(const void*, const void*)' 的无效转换
【发布时间】:2015-01-23 10:31:08
【问题描述】:

在编译我的 C 文件时,我收到以下错误:

error: invalid conversion from 'void*' to 'int (*)(const void*, const void*)'
error:   initializing argument 1 of 'void* bsearch(int (*)(const void*, const void*))'

下面是一些sn-ps的代码:

static int
testfucn(const char *func, const teststruct *array)
{
  return (strcmp(func, array->name));
}

int
test(char *fcn)
{
    if (bsearch((void*)testfucn))
        return(1);
    else
        return(0);
}

bsearch((void*)testfucn) 行出现错误

您能否建议此代码有什么问题以及如何解决此问题。

【问题讨论】:

标签: c


【解决方案1】:

错误非常明确 - 您传入了 void*(通过显式转换获得),而函数需要 int (*)(const void*, const void*)。没有从“指向void 的指针”到“指向函数的指针”的隐式转换,因此会出现错误。

我相信您可以将函数转换为请求的类型:

bsearch((int (*)(const void*, const void*)testfucn);

但是,请注意,虽然它可能(似乎)在实践中起作用,但它会调用未定义的行为。

正确的、类型安全的解决方案是实际声明一个具有适当签名的函数,可能是作为真实函数的包装器:

static int
testfucn_for_bsearch(const void *func, const void *array)
{
  return testfucn(func, array);
}

/* ... */

bsearch(testfucn_for_bsearch);

【讨论】:

  • IIRC,调用转换为不同类型的函数是未定义的。
  • @molbdnilo 足够公平,重新措辞
  • 谢谢@Angrew。添加 (int ()(const void, const void*)) 有效!!
  • @user1138143 请注意,这是一种解决方法,而不是解决方案。
【解决方案2】:

移除演员表。不能在数据(void *)和函数指针之间进行转换,参数应该是函数指针。

同时修复函数的签名,它与 bsearch() 回调的预期签名不匹配。请参阅the manual page 以获取正确的签名。

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多