Reputation: 1
I am trying to write C code to create a two-dimensional array of function pointers, where every function takes no arguments and returns int
.
I have already tried this code:
int *(*table())[10];
but it didn't work. Do you have any idea how can I fix it?
Upvotes: 0
Views: 309
Reputation: 213799
Regarding what the declaration you came up with does, that's a pretty icky declaration. You can unwind it with the clockwise/spiral rule.
Basically the table()
part means there's a a function. The ()
is obsolete C, meaning a function taking any parameter. You should be using (void)
instead.
The int* (* ... ) [10]
part means that you have a function returning an array pointer to an array int* [10]
. Such an array pointer is normally declared as int* (*name)[10]
when written outside a function return value.
So you have a function declaration, of a function returning an array pointer, to an array of 10 int*, the function is taking an obsolete style parameter list.
You can understand it better with this example:
typedef int* (*arrptr)[10]; // to illustrate, typedef an array pointer int* (*)[10]
typedef arrptr func_t (void); // typedef a function type returning said array pointer
void func (func_t* x){}
// dummy function to demonstrate type compatibility, funct_t* is a function pointer
int *(*table(void))[10]; // function declaration
int main (void)
{
func(table); // table is of same type as the function pointer func_t*
return 0;
}
int *(*table(void))[10]
{
return 0;
}
Please note that hiding arrays and pointers behind typedefs is normally bad practice.
Regarding how to get an array of function pointers, it is way more straight-forward than interpreting the above gibberish.
int* func (void)
This is a function.int* (*func) (void)
This is a function pointer to such a function.int* (*func[10][10]) (void)
This is a 2D array of function pointers.Or preferably:
typedef int* func_t (void)
This is a function type.func_t* fptr
This is a function pointer to such a function.func_t* fptr[10][10]
This is a 2D array of function pointers.Upvotes: 1
Reputation: 171127
C declarations are built such that typing the declarators as an expression yields the type. So, let's assume we already have such a 2D array a
. How to get int
out of it?
a[10]
.a[10][10]
*a[10][10]
int
: (*a[10][10])()
So the final declaration is:
int (*a[10][10])(void);
Of course, as usual, it's much easier with typedef
s:
typedef int Fun(void);
typedef Fun *FunPtr;
FunPtr a[10][10];
Upvotes: 3