gpt4 book ai didi

c - 如何制作指向具有不同参数数量的函数的函数指针?

转载 作者:太空狗 更新时间:2023-10-29 15:31:20 25 4
gpt4 key购买 nike

我正在尝试实现一个简单的函数指针程序,但我收到了这个警告:

Warning: assignment from incompatible pointer type while assigning function address to function pointer

我的程序如下:

#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;
}

最佳答案

将指针声明为指向无原型(prototype)函数(采用未指定数量参数的函数)的指针:

  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;
}
/*...*/

对于原型(prototype)函数,函数指针类型之间的匹配需要或多或少准确(有一些警告,例如顶级限定符无关紧要,或者可以用不同的方式拼写),否则标准会留下未定义的东西.

或者,考虑到无原型(prototype)函数和函数指针是过时的特性,您可以使用强类型指针(首先是 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;
}
/*...*/

关于c - 如何制作指向具有不同参数数量的函数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com