简体   繁体   English

数组和函数指针

[英]Arrays and function pointers

How do pass an array of pointers to functions as a argument to a function?如何将指向函数的指针数组作为参数传递给函数? If the types of the functions are void and so is the pointer, how do you access the functions?如果函数的类型是空的,指针也是空的,你如何访问这些函数?

int main() {

  void(*fun_ptr[])(void) = {fun1, fun2, fun3};
  pickFun(fun_ptr);
  return 0;
}

All 3 functions only print a message and are declared as void所有 3 个函数只打印一条消息并声明为 void

void pickFun(void *function_ptr[])
{
   int pick = 0;
   while(pick != 0)
   {
     scanf("%i", &pick);
    *(function_ptr + (pick - 1));
   }
 }

I can never get the function's printf statements to appear when a function is chosen.选择函数时,我永远无法显示函数的 printf 语句。 The program just loops and never prints the message contained in each function.程序只是循环,从不打印每个函数中包含的消息。 Any suggestions or clues?有什么建议或线索吗?

Function parameter void *function_ptr[] is of type pointer to pointer to void`.函数参数void *function_ptr[]pointer to pointer to void` 的pointer to pointer to的类型。 You need to change it to你需要把它改成

void pickFun(void (*function_ptr[])(void));  

Also note that, as others pointed out in comments, program never enters the loop body.另请注意,正如其他人在评论中指出的那样,程序永远不会进入循环体。 Better to use do while loop here最好do while这里使用do while循环

void pickFun(void *function_ptr[])
{
   do
   {
        scanf("%i", &pick);
        //*(function_ptr + (pick - 1));
        function_ptr[pick-1]();     //Function call. pick should not be greater than 3
   } while(pick != 0)
 }

Also, you can call your functions with:此外,您可以通过以下方式调用您的函数:

(*function_ptr[pick-1])();

or (yuck):或(糟糕):

(*(function_ptr + (pick-1)))();

or:或者:

function_ptr[pick-1]();

or:或者:

(function_ptr + (pick-1))();

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

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