What does the following code do? [duplicate]
Possible Duplicate:
How do you read C declarations?
I Don't understand the following:
int * (*(*p)[2][2])(int,int);开发者_JS百科
Can you help?
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
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.
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)
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;
精彩评论