Shi*_*hra 5 c function-pointers function
我最近在读代码,发现函数指针写成:
int (*fn_pointer ( this_args ))( this_args )
Run Code Online (Sandbox Code Playgroud)
我经常会遇到这样的函数指针:
return_type (*fn_pointer ) (arguments);
Run Code Online (Sandbox Code Playgroud)
这里讨论类似的事情:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我有什么区别,这是如何工作的?
hac*_*cks 10
int (*fn_pointer ( this_args ))( this_args );
Run Code Online (Sandbox Code Playgroud)
声明fn_pointer为一个函数,它接受this_args并返回一个指向函数的指针,该函数this_args作为参数并返回一个int类型.它相当于
typedef int (*func_ptr)(this_args);
func_ptr fn_pointer(this_args);
Run Code Online (Sandbox Code Playgroud)
让我们更多地了解它:
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
Run Code Online (Sandbox Code Playgroud)
如何阅读 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
Run Code Online (Sandbox Code Playgroud)
所以,最后一个家庭工作:).试着找出声明
void (*signal(int sig, void (*func)(int)))(int);
Run Code Online (Sandbox Code Playgroud)
并用typedef它来重新定义它.