[英]error: invalid conversion from 'void*' to 'int (*)(const void*, const void*)'
While compiling my C file, I am getting the below error: 编译C文件时,出现以下错误:
error: invalid conversion from 'void*' to 'int (*)(const void*, const void*)'
error: initializing argument 1 of 'void* bsearch(int (*)(const void*, const void*))'
Below are some code snippets: 以下是一些代码片段:
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);
}
Error is coming for the line bsearch((void*)testfucn)
bsearch((void*)testfucn)
行出现错误
Could you please suggest what is wrong with this code and how to resolve this issue. 您能否建议此代码出了什么问题以及如何解决此问题。
The error is pretty explicit - you're passing in a void*
(obtained by your explicit cast) while the function expects an int (*)(const void*, const void*)
. 该错误是非常明显的-您正在传递void*
(由您的显式强制转换获得),而该函数需要一个int (*)(const void*, const void*)
。 There is no implicit conversion from 'pointer to void
' to 'pointer to a function', hence the error. 没有从'pointer to void
'到'pointer to a function'的隐式转换,因此出错。
I believe you could get away with casting the function to the requested type: 我相信您可以将函数强制转换为所需的类型:
bsearch((int (*)(const void*, const void*)testfucn);
However, note that while it might (appear to) work in practice, it would invoke Undefined Behaviour. 但是,请注意,尽管它可能(看起来)在实践中可行,但会调用未定义的行为。
The correct, type-safe solution is to actually declare a function with the appropriate signature, possibly as a wrapper around your real function: 正确的类型安全的解决方案是实际声明具有适当签名的函数,可能将其包装为您的真实函数:
static int
testfucn_for_bsearch(const void *func, const void *array)
{
return testfucn(func, array);
}
/* ... */
bsearch(testfucn_for_bsearch);
Remove the cast. 删除演员表。 You can't cast between data ( void *
) and function pointers, and the argument should be a function pointer. 您不能在数据( void *
)和函数指针之间进行强制转换,并且参数应为函数指针。
Also fix your function's signature, it doesn't match the expected signature of a bsearch()
callback. 还要修复函数的签名,它与bsearch()
回调的预期签名不匹配。 See the manual page for the proper signature. 有关正确的签名,请参见手册页 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.