如何在c中传递函数指针到函数?


#include "stdio.h"
int add(int x, int y)
{
return x + y;
}
int withFive(int x, int (*func))
{
return (*func)(x,5);
}
int main()
{
void (*funcptr)(int) = &add;
printf("%d", withFive(10,funcptr));
return 0;
}

这段代码似乎会根据我对函数指针的理解来编译,但是有一个函数或函数指针没有传递给withFive的错误。我该如何写withFive,使编译器将接受参数作为一个函数ptr?

定义应为

int withFive(int x, int (*func)(int, int ) )

int withFive(int x, int (*func)(int x, int y) )

像变量定义中的

Btw:void (*funcptr)(int) = &add;应该是int (*funcptr)(int,int) = &add;或者只是int (*funcptr)(int,int) = add;

int withFive(int x, int (*func))

你想要一个函数func作为参数,它返回int,并接受两个int作为参数

所以你需要:

int withFive(int x, int (*func)(int, int))

:

{
return (*func)(x,5);
}

您不需要取消对func的引用。只写

return func(x, 5);

:

void (*funcptr)(int) = &add;

又打错了。你不需要取add的地址。只写:

int (*funcptr)(int, int) = add;

或者直接写

printf("%d", withFive(10,add));

一般来说,为了更容易地处理有些笨拙的函数指针语法,并使结果更具可读性,您可以使用typedef。所有这些,以及其他一些小的编辑包括:

#include <stdio.h>
typedef int (*binary_func_t)( int, int );
int add( int x, int y )
{
return x + y;
}
int withFive( int x, binary_func_t func )
{
return func( x, 5 );
}
int main()
{
printf( "%dn", withFive( 10, add ) );
return 0;
}

在您的情况下,它必须是int withFive(int x, int (*func)(int,int))。然而,使用C的原始函数指针语法是相当不可读的。推荐的做法是始终使用typedef,如下所示:

typedef int operation_t (int x, int y); // function type acting as "template"
int add (int x, int y);
int withFive(int x, operation_t* op); // op is a pointer to function
...
withFive(10, add);

最新更新