pro*_*eek 7 c c++ function-pointers
我碰巧遇到了以下函数指针.
char (*(*x())[])();
Run Code Online (Sandbox Code Playgroud)
它看起来像以下格式的函数指针数组,但我看不出f - >(*x())的含义.如何解释这个凌乱的函数指针?
char (*f[])();
Run Code Online (Sandbox Code Playgroud)
在John Bode的帮助下,我举了一个例子如下.
#include <stdio.h>
char foo() { return 'a'; }
char bar() { return 'b'; }
char blurga() { return 'c'; }
char bletch() { return 'd'; }
char (*gfunclist[])() = {foo, bar, blurga, bletch};
char (*(*x())[])()
{
static char (*funclist[4])() = {foo, bar, blurga, bletch};
return &funclist;
}
int main()
{
printf("%c\n",gfunclist[0]());
char (*(*fs)[4])();
fs = x();
printf("%c\n",(*fs)[1]());
}
Run Code Online (Sandbox Code Playgroud)
我可以得到预期的结果.
smcho@prosseek temp2> ./a.out a b
而且,您可以在此处找到更好的实施方案.
Joh*_*ode 12
我的一般过程是在声明中找到最左边的标识符,然后解决这个问题,记住它[]并()在之前绑定*(即,*f()通常被解析为*(f())并且*a[]通常被解析为*(a[])).
所以,
x -- x
x() -- is a function
*x() -- returning a pointer
(*x())[] -- to an array
*(*x())[] -- of pointers
(*(*x())[])() -- to functions
char (*(*x())[])(); -- returning char
Run Code Online (Sandbox Code Playgroud)
这种野兽在实践中会是什么样子?
char foo() { return 'a'; }
char bar() { return 'b'; }
char blurga() { return 'c'; }
char bletch() { return 'd'; }
/**
* funclist -- funclist
* funclist[] -- is an array
* *funclist[] -- of pointers
* (*funclist[])() -- to functions
* char (*funclist[])() -- returning char
*/
char (*funclist[])() = {foo, bar, blurga, bletch};
Run Code Online (Sandbox Code Playgroud)
表达式&funclist将返回指向数组的指针,所以
char (*(*x())[])()
{
return &funclist;
}
Run Code Online (Sandbox Code Playgroud)
char (*(*x())[])();
Run Code Online (Sandbox Code Playgroud)
x is a function returning pointer to array of pointer to function returning char
char (*f[])();
Run Code Online (Sandbox Code Playgroud)
在这种情况下 f is an array of pointer to function returning char
使用左右规则将是有益的.
cdecl> explain char (*(*x())[])();
declare x as function returning pointer to array of pointer to function returning char
Run Code Online (Sandbox Code Playgroud)