4

Possible Duplicate:
How do you read C declarations?

I Don't understand the following:

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

Can you help?

Community
  • 1
  • 1
Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141
  • +1 Cos although I thought it was not a terribly interesting question, have learnt about cdecl from Ismail. John Bode's answer shows how to do it in your head, and I have learnt that rather than rushing to get an answer I can actually do in as quickly as possible, that maybe quality wins out in the end. – aronp Jan 14 '11 at 19:21

4 Answers4

18

For things like this try cdecl, decoded to;

declare p as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int
ismail
  • 46,010
  • 9
  • 86
  • 95
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

What would such a beast look like in practice?

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.
John Bode
  • 119,563
  • 19
  • 122
  • 198
4

Pretty sure its defining p as a pointer to a 2 by 2 array of pointers to (functions taking (int a, int b) as parameters and returning a pointer to int)

aronp
  • 799
  • 2
  • 6
  • 14
2

The expression defines a pointer to an 2x2 array of function pointers. See http://www.newty.de/fpt/fpt.html#arrays for an introduction to C/C++ function pointers (and arrays of them specifically).

In particular, given a function declaration

int* foo(int a, int b);

You define a function pointer ptr_to_foo (and assign the address of foo to it) like this:

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

Now, if you need not only a single function pointer, but an array of them (let's make this a 2D array of size 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 */

Apparently, that's not enough. Instead of the array of function pointers, we need a pointer to such an array. And that would be:

int* (*(*p)[2][2])(int, int);
p = &array_of_ptr_to_foo;
Daniel Gehriger
  • 7,339
  • 2
  • 34
  • 55