在c中,請考慮這種情況。我有一個函數指針數組,我想調用它們中的每一個。我也有一個整數數組,告訴我每個參數需要多少個參數。我第三次有一組我想要調用它們的參數。下面的程序是使用此一程序的一個例子:如何在調用運行時知道參數數量的情況下如何調用函數指針
int foo(int a, int b, int c){
return a+b+c;
}
int bar(int a, int b){
return a+b;
}
int baz(int a){
return a;
}
int qux(){
return 0;
}
int main(){
void *funcArray[4] = {foo, bar, baz, qux}; //an array of function pointers, all of which return ints but have different numbers of arguments
int argArray[3+2+1+0] = {100,30,1, 20,7, 9}; //these are the arguments to the functions to be executed
int numArgsArray[4] = {3,2,1,0}; //these are the numbers of arguments that each function takes in the funcArray array
int nextArg = 0; //used to keep track of which argument goes to which function
for (int i = 0; i<4; i++){
int result;
switch(numArgsArray[i]){
case 0://if the function takes no args, just call it
result = ((int(*)())funcArray[i])();
break;
case 1://if the function takes one arg, pass it the argument when calling it
result = ((int(*)(int))funcArray[i])(argArray[nextArg]);
nextArg += 1;
break;
case 2://if the function takes two arguments, pass it both when calling
result = ((int(*)(int, int))funcArray[i])(argArray[nextArg], argArray[nextArg+1]);
nextArg += 2;
break;
case 3://if the function takes three args, pass it all three when calling
result = ((int(*)(int, int, int))funcArray[i])(argArray[nextArg], argArray[nextArg+1], argArray[nextArg+2]);
nextArg += 3;
break;
}
printf("%d\n", result);
}
return 0;
}
上述程序工作,並將其輸出:這是intented輸出。問題是我需要在switch語句中爲每個我想支持的參數個數設置一個大小寫。 所以我的問題是:有沒有一個更簡單的方法來做到這一點,這不是很難看,並將與任何數量的參數一起工作?
注意:在標準C中不允許從'pointer to function'到'void *'的轉換。 – BLUEPIXY 2014-09-29 01:54:32
實現一個輕量級向量並將指針傳給它。 – 2014-09-29 01:54:56
只需將argc和argv傳遞給函數即可。 – chux 2014-09-29 01:57:32