我正在尝试实现一个简单的函数指针程序,但是我收到了这个警告:
警告:在将函数地址分配给函数指针
时从不兼容的指针类型进行赋值
我的计划如下:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int add(int a, int b);
int sub(int a, int b);
int Add3Num(int a, int b, int c);
int main(int argc, char *argv[]) {
int (*func)(int , ...);
int a = 20, b = 10, c = 5, result;
func = add;
result = func(a, b); // Warning over here
printf("Result of 20 + 10 = %d\n", result);
func = sub;
result = func(a, b); // Warning over here
printf("Result of 20 - 10 = %d\n", result);
func = Add3Num;
result = func(a, b, c); // Warning over here
printf("Result of 20 + 10 + 5 = %d\n", result);
return 0;
}
int add(int a, int b){
return a+b;
}
int sub(int a, int b){
return a-b;
}
int Add3Num(int a, int b, int c){
return a+b+c;
}
答案 0 :(得分:4)
将指针声明为指向无原型函数的指针(一个函数采用未指定数量的参数):
int (*func)();
然后你的程序应该工作,without any need for casts(只要每次调用继续匹配当前指向的函数)。
#include <stdio.h>
int add(int a, int b);
int sub(int a, int b);
int Add3Num(int a, int b, int c);
int main(){
int (*func)(); /*unspecified number of arguments*/
int a = 20, b = 10, c = 5, result;
/*Casts not needed for these function pointer assignments
because: https://stackoverflow.com/questions/49847582/implicit-function-pointer-conversions */
func = add;
result = func(a, b);
printf("Result of 20 + 10 = %d\n", result);
func = sub;
result = func(a, b);
printf("Result of 20 - 10 = %d\n", result);
func = Add3Num;
result = func(a, b, c);
printf("Result of 20 + 10 + 5 = %d\n", result);
return 0;
}
/*...*/
使用原型函数,函数指针类型之间的匹配需要或多或少精确(有一些注意事项,如顶级限定符无关紧要或事物可以拼写不同),否则标准将事物定义为不确定
或者,也许最好假设无原型函数和函数指针是一个过时的特性,你可以使用强类型指针(第一个int (*)(int,int)
然后int (*)(int,int,int)
)并使用强制转换强制事物。
#include <stdio.h>
int add(int a, int b);
int sub(int a, int b);
int Add3Num(int a, int b, int c);
int main(){
int (*func)(int , int);
int a = 20, b = 10, c = 5, result;
func = add;
result = func(a, b);
printf("Result of 20 + 10 = %d\n", result);
func = sub;
result = func(a, b);
printf("Result of 20 - 10 = %d\n", result);
/*cast it so it can be stored in func*/
func = (int (*)(int,int))Add3Num;
/*cast func back so the call is defined (and compiles)*/
result = ((int (*)(int,int,int))func)(a, b, c);
printf("Result of 20 + 10 + 5 = %d\n", result);
return 0;
}
/*...*/