【问题标题】:What does the following code do? [duplicate]下面的代码有什么作用? [复制]
【发布时间】:2026-02-25 14:30:01
【问题描述】:

可能重复:
How do you read C declarations?

我不明白以下内容:

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

你能帮忙吗?

【问题讨论】:

  • +1 Cos 虽然我认为这不是一个非常有趣的问题,但从 Ismail 那里了解了 cdecl。 John Bode 的答案在您的脑海中展示了如何做到这一点,而且我了解到,与其急于得到答案,我实际上可以尽快做到,也许质量最终会胜出。

标签: c cdecl


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
              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.
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        表达式定义了一个指向 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;
        

        【讨论】: