gpt4 book ai didi

c - 在c中写一个函数指针

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

最近在看一段代码,发现一个函数指针是这样写的:

int (*fn_pointer ( this_args ))( this_args )

我经常遇到这样的函数指针:

return_type (*fn_pointer ) (arguments);

讨论了类似的事情here :

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}

谁能告诉我有什么区别以及它是如何工作的?

最佳答案

int (*fn_pointer ( this_args ))( this_args );  

fn_pointer 声明为一个接受 this_args 并返回一个指针的函数,该函数接受 this_args 作为参数并返回一个 int 类型。相当于

typedef int (*func_ptr)(this_args);
func_ptr fn_pointer(this_args);

让我们多了解一下:

int f1(arg1, arg2);  // f1 is a function that takes two arguments of type   
// arg1 and arg2 and returns an int.

int *f2(arg1, arg2); // f2 is a function that takes two arguments of type
// arg1 and arg2 and returns a pointer to int.

int (*fp)(arg1, arg2); // fp is a pointer to a function that takes two arguments of type
// arg1 and arg2 and returns a pointer to int.

int f3(arg3, int (*fp)(arg1, arg2)); // f3 is a function that takes two arguments of
// type arg3 and a pointer to a function that
// takes two arguments of type arg1 and arg2 and
// returns an int.

int (*f4(arg3))(arg1, arg2); // f4 is a function that takes an arguments of type
// arg3 and returns a pointer to a function that takes two
// arguments of type arg1 and arg2 and returns an int

How to read int (*f4(arg3))(arg1, arg2);

          f4                           -- f4
f3( ) -- is a function
f3(arg3) -- taking an arg3 argument
*f3(arg3) -- returning a pointer
(*f3(arg3))( ) -- to a function
(*f3(arg3))(arg1, arg2) -- taking arg1 and arg2 parameter
int (*f3(arg3))(arg1, arg2) -- and returning an int

所以,最后一个家庭作业:)。试着弄清楚声明

void (*signal(int sig, void (*func)(int)))(int);  

并使用 typedef 重新定义它。

关于c - 在c中写一个函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583879/

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