如何使用函数指针调用函数?

问题描述 投票:35回答:16

假设我具有这三个功能:

bool A();
bool B();
bool C();

如何使用功能指针有条件地调用这些功能之一,以及如何声明功能指针?

c function-pointers
16个回答
39
投票

您可以执行以下操作:假设您具有以下A,B和C函数:

bool A()
{
   .....
}

bool B()
{
   .....
}

bool C()
{

 .....
}

现在在其他功能上,在main处说:

int main()
{
  bool (*choice) ();

  // now if there is if-else statement for making "choice" to 
  // point at a particular function then proceed as following

  if ( x == 1 )
   choice = A;

  else if ( x == 2 )
   choice = B;


  else
   choice = C;

if(choice())
 printf("Success\n");

else
 printf("Failure\n");

.........
  .........
  }

请记住,这是函数指针的一个示例。还有其他几种方法,您必须清楚地学习函数指针。


1
投票

您为函数的给定签名声明一个函数指针变量,如下所示:

bool (* fnptr)();

您可以为其分配功能之一:

fnptr = A;

您可以称之为:

bool result = fnptr();

您可能考虑使用typedef为所需的每个不同函数签名定义类型。这将使代码更易于阅读和维护。即对于不带参数返回bool的函数的签名,可能是:

typdef bool (* BoolFn)();

然后您可以像这样使用此类型声明函数指针变量:

BoolFn fnptr;

1
投票

略有不同的方法:

bool A() {...}
bool B() {...}
bool C() {...}

int main(void)
{
  /**
   * Declare an array of pointers to functions returning bool
   * and initialize with A, B, and C
   */
  bool (*farr[])() = {A, B, C};
  ...
  /**
   * Call A, B, or C based on the value of i
   * (assumes i is in range of array)
   */
  if (farr[i]()) // or (*farr[i])()
  {
    ...
  }
  ...
}

1
投票

如果需要复杂定义的帮助,例如:

double (*(*pf)())[3][4];

看看我的右左规则here


0
投票
//Declare the pointer and asign it to the function
bool (*pFunc)() = A;
//Call the function A
pFunc();
//Call function B
pFunc = B;
pFunc();
//Call function C
pFunc = C;
pFunc();

0
投票

我通常使用typedef来执行此操作,但是如果您不必过于频繁地使用函数指针,则可能会过大。.

//assuming bool is available (where I come from it is an enum)

typedef bool (*pmyfun_t)();

pmyfun_t pMyFun;

pMyFun=A; //pMyFun=&A is actually same

pMyFun();

0
投票

答案已经足够充分,但是您可能会发现这很有用:The Function Pointer Tutorials。在五个章节中,它是对该主题的真正全面处理!


0
投票

通过函数指针调用函数

float add(int , float),result;
int main()
{
 float (*fp)(int,float);
 float result;
 fp=add;
 result=add(5,10.9);      // Normal calling
 printf("%f\n\n",result);

 result=(*fp)(5,10.9);    //calling via function Pointer
 printf("%f\n\n",result);

 result=(fp)(5,10.9);    //calling via function Pointer,Indirection Operator can Be 
 omitted
 printf("%f",result);
 getch();
 }

float add(int a,float b)
{
return a+b;
}

输出

15.90000
15.90000
15.90000

23
投票

这样声明函数指针:

bool (*f)();
f = A;
f();

18
投票

我认为您的问题已经得到了足够的答案,但是明确指出给定的函数指针可能会很有用

void (*pf)(int foo, int bar);

两个电话

pf(1, 0);
(*pf)(1, 0);

根据定义在各方面都完全相同。使用哪种选择取决于您,尽管保持一致是一个好主意。很长时间以来,我更喜欢(*pf)(1, 0),因为在我看来它更好地反映了pf的类型,但是在最近几年中,我切换到了pf(1, 0)


14
投票

最初定义一个函数指针数组,该数组将获取一个void并返回一个void。假设您的函数正在获取一个void并返回一个void。

typedef void (*func_ptr)(void);

现在,您可以使用它来创建此类函数的函数指针变量。如下所示:

func_ptr array_of_fun_ptr[3];

现在将函数的地址存储在三个变量中。

array_of_fun_ptr[0]= &A;
array_of_fun_ptr[1]= &B;
array_of_fun_ptr[2]= &C;

现在您可以使用以下函数指针来调用这些函数:

some_a=(*(array_of_fun_ptr[0]))();
some_b=(*(array_of_fun_ptr[1]))();
some_c=(*(array_of_fun_ptr[2]))();

6
投票

您可以如下声明函数指针:

bool (funptr*)();

哪个说我们正在声明一个指向不带任何内容并返回布尔值的函数的函数指针。

下一次作业:

funptr = A;

使用函数指针调用函数:

funptr();

4
投票
bool (*FuncPtr)()

FuncPtr = A;
FuncPtr();

如果要有条件地调用这些功能之一,则应考虑使用array of function pointers。在这种情况下,您将有3个指向A,B和C的元素,并且根据数组的索引调用一个元素,例如A的funcArray0。


2
投票
bool (*fptr)();

int main(void)
{
  ...
  ...
  printf("Enter your choice");
  scanf("%d",&a);
  switch(a)
{
  case 0:
         fptr = A;
         break;
  case 1:
         fptr = B;
         break;
  case 2:
         fptr = C;
         break;
  case 3:
          break;
}
(*fptr)();
return 0;
}

您的选择存储在然后,相应地,在功能指针中分配功能。最后,根据您的选择,调用完全相同的函数以返回所需的结果。


2
投票

请注意,当您说:

bool (*a)();

您声明的是a类型的“指向返回bool并采用未指定数量的参数的函数的指针”。假设已定义bool(也许您正在使用C99并且包含了stdbool.h,或者它可能是typedef),则可能不是您想要的。

这里的问题是,编译器现在无法检查a是否分配了正确的值。您的函数声明存在相同的问题。 A()B()C()都被声明为函数“返回bool并使用未指定数量的参数”。

要查看可能出现的问题的种类,让我们编写一个程序:

#include <stdio.h>

int test_zero(void)
{
    return 42;
}

static int test_one(char *data)
{
    return printf("%s\n", data);
}

int main(void)
{
    /* a is of type "pointer to function returning int
       and taking unspecified number of parameters */
    int (*a)();

    /* b is of type "pointer to function returning int
       and taking no parameters */
    int (*b)(void);

    /* This is OK */
    a = test_zero;
    printf("a: %d\n", a());

    a = test_one; /* OK, since compiler doesn't check the parameters */
    printf("a: %d\n", a()); /* oops, wrong number of args */

    /* This is OK too */
    b = test_zero;
    printf("b: %d\n", b());

    /* The compiler now does type checking, and sees that the
       assignment is wrong, so it can warn us */
    b = test_one;
    printf("b: %d\n", b()); /* Wrong again */

    return 0;
}

当我用gcc编译上面的内容时,它说:

警告:来自不兼容指针类型的分配

对于行b = test_one;,这很好。 a的相应分配没有警告。

因此,您应该将函数声明为:

bool A(void);
bool B(void);
bool C(void);

然后用于保存功能的变量应声明为:

bool (*choice)(void);

2
投票

最好的阅读方式是``顺时针/螺旋规则''

[通过大卫·安德森

http://c-faq.com/decl/spiral.anderson.html

© www.soinside.com 2019 - 2024. All rights reserved.