繁体   English   中英

如何创建一个指向具有不同参数数量的函数的函数指针?

[英]How can I make a function pointer that points to functions with different number of arguments?

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

警告:在将函数地址分配给函数指针时从不兼容的指针类型进行赋值

我的计划如下:

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

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

  int (*func)();

然后你的程序应该工作, 而不需要演员表 (只要每个调用继续匹配当前指向的函数)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM