gpt4 book ai didi

c - 如何为接受函数指针的函数提供参数

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:02 24 4
gpt4 key购买 nike

我正在尝试做这样的事情:

void print (int number)
{
printf("Argument \"%i\" has been given", number);
}

void foo (void (*ptr)(int arg))
{
ptr(arg);
}

int main (void)
{
foo(print(10));

return 0;
}

这不太可能奏效,因为 print(10) 应该返回 void,而不是实际的函数地址。但至少我希望我的问题是可以理解的,因为我很难解释它用简单的话。


如何在这样的函数指针中传递参数?

最佳答案

你不能“像那样在函数指针中传递参数”。你可以做的是传递一个额外的参数来匹配你的函数指针期望的参数。

这看起来像这样:

void print (int number)
{
printf("Argument \"%i\" has been given", number);
}

void foo (void (*ptr)(int), int arg) // the new argument is here.
{
ptr(arg);
}

int main (void)
{
foo(print, 10);

return 0;
}

备选

我们在这里所做的是将参数和函数指针打包到一个结构中,并将该结构传递给 foo()。这有点类似于c++的std::bind但简化且功能较弱。

typedef struct bind_s
{
void (*ptr)(int);
int arg;
} bind_t;

void print (int number)
{
printf("Argument \"%i\" has been given", number);
}

void foo (bind_t call)
{
call.ptr(call.arg);
}

int main (void)
{
bind_t call = {print, 10};
foo(call);

return 0;
}

关于c - 如何为接受函数指针的函数提供参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29980512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com