我有两个具有相同参数和返回类型的函数。 喜欢
int fun1(int a){
return a+1;
}
int fun2(int a){
return a+2;
}
我创建了一个函数指针int(*funptr)(int)
。
我想使用malloc
并使funptr[0]
指向fun1
和funptr[1]
code> 指向 fun2
。
所以我尝试了
int(*funptr)(int)=(int*)malloc(2*sizeof(funptr));
但它不起作用。我能做什么?
最佳答案
我的理解是你需要一个函数指针数组。改变
int(*funptr)(int)
至
int (*funptr)[2] (int)
并使用funptr[0] = fun1;
和funptr[1] = fun2;
或者,如果必须使用分配的内存,则可以使用指向函数指针的指针
int (**funptr)(int);
然后相应地使用。为了便于使用,请使用 typedef
。
typedef int(*funptr)(int);
funptr * fp;
fp = malloc(2* sizeof*fp);
fp[0] = fun1;
fp[1] = fun2;
关于c - 我想为函数指针分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62194024/