4

可能重复:
您如何阅读 C 声明?

我不明白以下内容:

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

你能帮我吗?

4

4 回答 4

18

对于这样的事情尝试cdecl,解码为;

declare p as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int
于 2011-01-14T10:20:43.507 回答
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.
于 2011-01-14T13:03:09.183 回答
4

很确定它将 p 定义为指向 2 x 2 指针数组的指针(函数以 (int a, int b) 作为参数并返回指向 int 的指针)

于 2011-01-14T10:24:53.463 回答
2

该表达式定义了一个指向 2x2 函数指针数组的指针。请参阅http://www.newty.de/fpt/fpt.html#arrays了解 C/C++ 函数指针(以及它们的数组)的介绍。

特别是,给定一个函数声明

int* foo(int a, int b);

您定义一个函数指针 ptr_to_foo (并将 foo 的地址分配给它),如下所示:

int* (*ptr_to_foo)(int, int) = &foo;

现在,如果您不仅需要单个函数指针,还需要它们的数组(让我们将其设为大小为 2 x 2 的 2D 数组):

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;
于 2011-01-14T10:45:27.740 回答