在c中编写函数指针

2023-12-02

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

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   

如何阅读 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);  

and use typedef重新定义它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在c中编写函数指针 的相关文章

随机推荐