在C语言中编写函数指针

5

我最近在读一段代码时发现,一个函数指针被写成了:

int (*fn_pointer ( this_args ))( this_args )

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

return_type (*fn_pointer ) (arguments);

类似的问题在这里讨论:

// 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;
}

有人可以告诉我这是什么区别,以及它是如何工作的吗?

你能否提供精确的代码?一个可编译的示例? - Iharob Al Asimi
1
这可能会有所帮助 https://dev59.com/nnRA5IYBdhLWcg3wwwvD?rq=1 - Arun A S
@iharob:我的代码更长了。我刚刚更新了。 - Shivendra Mishra
3个回答

10
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);  

并使用 typedef 对其进行重新定义。


哪一个是参数,哪一个是返回值? - Shivendra Mishra

4
从C声明的辅助工具cdecl中:
int (*fn_pointer ( this_args1 ))( this_args2 )

声明fn_pointer为一个函数,该函数返回指向另一个函数的指针,该函数返回int类型。

因此,前者是一个函数,它返回指向函数的指针,而后者:

return_type (*fn_pointer ) (arguments);

是一个普通的“指向函数”的指针。


Clockwise/Spiral Rule文章中了解更多关于理解复杂声明的内容。


2
在这个声明中,fn_pointer不是一个指针(只是一个函数)。 - Wintermute

2

This

int (*fn_pointer ( this_args1 ))( this_args2 )

声明一个函数,它带有参数this_args1,并返回类型为函数指针的函数。

int (*fn_pointer)(this_args2)

所以它只是返回函数指针的函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接