以下代码是做什么的?

4
我不明白以下内容:

可能是重复问题:
如何阅读C语言声明?

请解释一下。

int‬‬ ‪* (*(*p)[2][2])(int,int);

Can you help?


虽然我认为这不是一个非常有趣的问题,但从Ismail那里学到了cdecl。John Bode的答案展示了如何在脑海中解决它,我学到了不要急于得出答案,而是可能质量最终会胜出。 - aronp
4个回答

18

尝试使用cdecl这样的工具。解码后为:

declare p as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int

16
          p                      -- p
         *p                      -- is a pointer
        (*p)[2]                  -- to a 2-element array
        (*p)[2][2]               -- of 2-element arrays
       *(*p)[2][2]               -- of pointers
      (*(*p)[2][2])(       );    -- to functions  
      (*(*p)[2][2])(int,int);    -- taking 2 int parameters
    * (*(*p)[2][2])(int,int);    -- and returning a pointer
int‬‬ ‪* (*(*p)[2][2])(int,int);    -- to int

这样的一个“野兽”在实践中会是什么样子呢?
int *q(int x, int y) {...}  // functions returning int *
int *r(int x, int y) {...}
int *s(int x, int y) {...}
int *t(int x, int y) {...}
...
int *(*fptr[2][2])(int,int) = {{p,q},{r,s}};  // 2x2 array of pointers to 
                                              // functions returning int *
...
int *(*(*p)[2][2])(int,int) = &fptr;          // pointer to 2x2 array of pointers
                                              // to functions returning int *
...
int *v0 = (*(*p)[0][0])(x,y);                 // calls q
int *v1 = (*(*p)[0][1])(x,y);                 // calls r
... // etc.

4

我相信它将p定义为指向一个2x2的指针数组,该数组包含指向函数(以(int a, int b)作为参数并返回int指针)的指针。


2
该表达式定义了一个指向2x2函数指针数组的指针。有关C/C++函数指针(以及特定的函数指针数组)的介绍,请参见http://www.newty.de/fpt/fpt.html#arrays
特别地,考虑以下函数声明:
int* foo(int a, int b);

你可以像这样定义一个函数指针ptr_to_foo(并将foo的地址分配给它):
int* (*ptr_to_foo)(int, int) = &foo;

现在,如果您不仅需要单个函数指针,而是一个数组(让我们将其制作为大小为2 x 2的二维数组):
int* (*array_of_ptr_to_foo[2][2])(int, int);
array_of_ptr_to_foo[0][0] = &foo1;
array_of_ptr_to_foo[0][1] = &foo2;
/* and so on */

显然,这还不够。我们需要一个指向这样一个数组的指针,而不是函数指针的数组。代码如下:
int* (*(*p)[2][2])(int, int);
p = &array_of_ptr_to_foo;

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