如何解决将指针与整数进行比较?
我需要知道我可以在 C 中做这样的事情。 我有 3 个这样的函数:
int fun1 ()
{if (condition)
{return 1;}
else
{return 0;}}
然后我有一个函数指针数组,我想将它与数字 1 进行比较(比较函数的结果!!)。
int (*fun_ptr[3])() = {fun1,fun2,fun3}; //all 3 functions in array
int i;
if ((*fun_ptr[i]) = 1)
{ //do something}
解决方法
假设您要调用一组函数以寻找其中一个返回 1 的函数:
请注意,要使该技术起作用,所有函数签名必须相同 - 在这种情况下,它们都返回 int 并接受 void。
更多示例:How can I use an array of function pointers?
int fun1 ()
{
// Place the condition you want to check here - might make more sense to pass it in as a parameter to all functions...
if (/*condition*/ 1)
{
return 1;
}
else
{
return 0;
}
}
// Assuming this functions would do something more useful in your case - PH so it compiles.
int fun2 () {return 0;}
int fun3 () {return 0;}
int main(void)
{
int (*func_ptr[3])() = {fun1,fun2,fun3}; //all 3 functions in array
// Loop through all functions - note we should use a sizeof() trick on the func_ptr array to be more correct on array size.
for(int i=0; i<3; i++)
{
// Call each function and check for "1"
if((*func_ptr[i])() == 1)
{
// If "1",do something
}
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。