指向多个函数的C指针
我想给一个函数传递一个指针,它可以指向几个函数中的一个 这个的语法是什么指向多个函数的C指针,c,function-pointers,C,Function Pointers,我想给一个函数传递一个指针,它可以指向几个函数中的一个 这个的语法是什么 void func_a(char c){ // } void func_b(char c){ // } void receiver( void (*function_pointer)(char) ){ // do stuff with the pointer to the function, e.g. call it: func
void func_a(char c){
//
}
void func_b(char c){
//
}
void receiver(
void (*function_pointer)(char)
){
// do stuff with the pointer to the function, e.g. call it:
function_pointer('a');
function_pointer('b');
function_pointer('c');
}
void main(){
receiver(&func_a); // calls func_a with 'a', then 'b', then 'c'
receiver(&func_b); // calls func_b with 'a', then 'b', then 'c'
}
以上工作是否如预期的那样?我假设函数指针只能用于具有相同签名的函数?是的,看起来它应该可以工作 是的,您只能对共享签名的函数使用单指针 小调: 您不需要使用&来获取函数的地址,函数的名称在适当的上下文中计算为其地址。 本地函数和仅用作回调函数func_a和func_b的函数应声明为静态函数。
你可以做的一件事就是使用typedef。在typedef中定义函数指针,您可以在参数中使用它。你也不需要&。使用您的代码创建一个示例
#include <stdio.h>
static void func_a(char c)
{
printf("a:%c\n", c);
}
static void func_b(char c)
{
printf("b:%c\n", c);
}
typedef void (*function)(char c);
void receiver( function func )
{
func('a');
func('b');
func('c');
}
void main()
{
receiver(func_a);
receiver(func_b);
}
我从“艰苦学习C”链接中学到了这一点:函数指针,用于在多个函数中选择一个函数
#include <stdio.h>
int plus(int a,int b){return a+b;}
int minus(int a,int b){return a-b;}
int multiply(int a,int b){return a*b;}
int divide(int a,int b){return a/b;}
int percentage(int a,int b){return a%b;}
void gec(int(**p)(int ,int),int c)
{
c=c%5;
if(c==0)
*p=plus;
else if(c==1)
*p=minus;
else if(c==2)
*p=multiply;
else if(c==3)
*p=divide;
else
*p=percentage;
}
int main(void) {
int a=100,b=20,c=12,r;
int(*fptr)(int,int)=NULL;
gec(&fptr,c);
r=(*fptr)(a,b);
printf("%d",r);
return 0;
}
你试过了吗?您是否遇到了错误,或者您只是好奇这是否正确?我曾经遇到过一个类似的问题,在文本文件上使用可选的可添加预处理器。您可以通过使用带有函子的结构和指向函数链中下一步的指针来解决此问题。然后,您可以使用whileprocessor{processor.exec;processor=processor.next;