On Tue, 14 Feb 2006, Olwe Bottorff wrote:
> I'm looking at a tutorial on function pointers and I
> see this code:
>
> typedef int (*pt2Function)(float, char, char);
> ...
> pt2Function funcArr1[10] = {NULL};
>
> So the typedef creates a variable called pt2Function
> that will house a pointer to a function.
No. It's giving a type a name. In this case, the name is pt2Function,
and the type is a pointer to a function that takes three arguments (a
float and two chars), and returns an int.
This stuff works on precendences- just like multiplication and division
happens before addition and subtraction, so that 3 + 4 * 5 is parsed as 3
+ (4 * 5) and not (3 + 4) * 5.
In this case, the (float, char, char) binds before the * does, so:
int * pt2Function(float, char, char);
binds like:
(int *) (pt2Function(float, char, char));
-i.e. a function returning a pointer to an int, not a pointer to a
function returning an int. So the parens above are necessary to "rebind"
the * correctly.
> That function
> takes parameters float, char, and char. Okay, but the
> int refers to the type of pt2Function, right? It's not
> saying that the function will eventually return an
> int, right?
It is saying that the function being pointed to will return an int.
>
> Also when the funcArr1 array is created it is created
> as type pt2Function of size 10. But what's going on
> with the {NULL} assignment? I'm pretty sure this is
> some sort of initialization, but a quick glance says
> it's initializing the 10th member of the array to NULL
> but not the first 9. I know that's not right, but what
> am I missing here?
This is bad form in C code. It'll work, but it's a bad idea. What he's
doing is initializing the *first* element in the array to NULL, and all
other elements to 0. There is no gaurentee that NULL is 0- just that
*casting* 0 to a pointer type results in NULL. This is generally true
however. So the code works, generally.
Brian