gpt4 book ai didi

c - 如何在函数实现中使用函数的函数参数?

转载 作者:太空狗 更新时间:2023-10-29 16:00:16 25 4
gpt4 key购买 nike

如果我有这样的声明:

int foo1 (int foo2 (int a));

如何实现这个foo1 函数?喜欢,

int foo1 (int foo2 (int a))
{
// How can I use foo2 here, which is the argument?
}

我如何调用 main 中的 foo1 函数?喜欢:

foo1(/* ??? */);

最佳答案

当您将函数参数声明为函数时,编译器会自动将其类型调整为“指向函数的指针”。

int foo1 (int foo2 (int a))

完全一样

int foo1 (int (*foo2)(int a))

(这类似于将函数参数声明为数组(例如 int foo2[123])如何自动使其成为指针(例如 int *foo2) .)

至于如何使用 foo2:您可以调用它(例如 foo2(42))或者取消引用它(*foo2 >),它(与函数一样)立即再次衰减回指针(然后您可以调用(例如 (*foo2)(42))或再次取消引用(**foo2 ),它立即衰减回一个指针,它...)。

要调用foo1,您需要向它传递一个函数指针。如果您周围没有现有的函数指针,您可以定义一个新函数(在 main 之外),例如:

int bar(int x) {
printf("hello from bar, called with %d\n", x);
return 2 * x;
}

然后你可以做

foo1(&bar);  // pass a pointer to bar to foo1

或等效

foo1(bar);  // functions automatically decay to pointers anyway

关于c - 如何在函数实现中使用函数的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55007980/

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