![](/img/trans.png)
[英]Function pointer pointing to functions with different number of arguments
[英]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.