
Pointer to an array of pointers to functions
Quote:
> I'm trying to create a data structure that contains a pointer
>to an array of function pointers.
Actually, I would bet this is *not* (quite) what you want.
This is one of those cases where it is important to distinguish
between:
array N of T
(for some integer constant N and valid element type T) and:
pointer to T, pointing to the first element of an array N of T,
i.e., the one with subscript 0
Remember that an actual object of type "array N of T" "decays" into
a value of type "pointer to T" in most contexts. Thus, if you want
a pointer that can point to the first element of this array, or to
any element within this array, you need an object of type "pointer
to T", *not* "pointer to array N of T".
So, if your array (named "A1", perhaps) has type:
array 10 of pointer to function (of void) returning void
or:
void (*A1[10])(void);
then a pointer that can point to its first element must have type:
pointer to function (of void) returning void
or:
void (*pf1)(void);
and it can be set with:
pf1 = A1;
or: pf1 = &A1[0];
On the other hand, if your array (A2?) has type:
array 5 of array 8 of pointer to function (of void) returning void
or:
void (*A2[5][8])(void);
then a pointer to its first element must have type:
pointer to array 8 of pointer to function (of void) returning void
(i.e., replace "array N of" with "pointer to"), or:
void (*(*pf2)[8])(void);
which can be set with:
pf2 = A2;
or: pf2 = &A2[0];
In this kind of case, people often resort to typedefs (which I
was just decrying earlier :-) but at least here they are not just
being pasted over "struct"s) to eliminate some of the parentheses.
(I am not going to supply examples, as I expect others will have
done so by now.)
Quote:
>Then to de-reference (that is call one of the functions):
> *pf[0] ();
If "pf3" has type:
pointer to function (of args) returning T
then a call to the function can be written most simply as:
val = pf3(args);
In K&R (pre-ANSI) C, some compilers required following the pointer
first, to obtain the function:
val = (*pf3)(args);
and many people still prefer to write it this way. ANSI C has
the peculiarity that the function immediately re-decays back into
another pointer, so that any number of prefix "*"s work:
val = (***********pf3)(args);
In the case of "pf2", however, it points to the first element of
an array (of size 8) of pointers to functions (of void, returning
void), so you would have to write:
pf2[i]();
or (K&R):
(*pf2[i])();
Since "prefix *" can be always converted to "suffix [0]" (that is,
*(p) and (p)[0] always "mean" the same thing), the "pf1" version
can be written as:
pf1();
(no arguments, no return value), or:
(*pf1)();
(K&R style); or
pf1[0]();
("odd-ified" style -- gcc generates a warning here, even though no
diagnostic is required), or even
pf1[0][0][0][0][0][0][0]();
(where gcc emits one warning per "[0]").
--
In-Real-Life: Chris Torek, Berkeley Software Design Inc