Connecting Tech Pros Worldwide Forums | Help | Site Map

Array of function pointers

sushil
Guest
 
Posts: n/a
#1: Nov 13 '05
+1 #include<stdio.h>
+2 #include <stdlib.h>
+3 typedef struct
+4 {
+5 unsigned int PID;
+6 unsigned int CID;
+7 } T_ID;
+8
+9 typedef unsigned int (*T_HANDLER)(void);
+10
+11 void Display1(void);
+12 void Display2(void);
+13
+14 int main()
+15 {
+16 T_HANDLER A_HANDLER[3] = { (T_HANDLER)Display1,
+17 (T_HANDLER)Display2};
+18
+19 (A_HANDLER[0])();
+20 (*A_HANDLER[1])();
^ Is this '*' required ?
+21 return 1;
+22 }
+23
+24 void Display1()
+25 {
+26 printf("\nDisplay1 called\n");
+27 }
+28
+29 void Display2()
+30 {
+31 printf("\nDisplay2 called\n");
+32 }
Hi,
I am new to group. I just tried to run a code with array of function pointer.
I could not understand why there is no error due to '*' at line no. 20.
Could anybody help me ?

Regards,
Sushil.

Jarno A Wuolijoki
Guest
 
Posts: n/a
#2: Nov 13 '05

re: Array of function pointers


On 4 Dec 2003, sushil wrote:
[color=blue]
> +19 (A_HANDLER[0])();
> +20 (*A_HANDLER[1])();
> ^ Is this '*' required ?[/color]

Not really, but it doesn't harm either.

[color=blue]
> I could not understand why there is no error due to '*' at line no. 20.
> Could anybody help me ?[/color]

Let's have

void f(void) {}
void (*pf)(void) = &f; /* ...= f goes as well. */

We get:

&f -> pointer to function
f -> function
pf -> pointer to function
*pf -> function

Now, like arrays, functions usually decay to pointers to them:

(&f)() -> (pointer to function)()
(f)() -> (function)() -> (pointer to function)()
(pf)() -> (pointer to function)()
(*pf)() -> (function)() -> (pointer to function)()

As well we get:

*(&f) -> *(pointer to function) -> function
*(f) -> *(function) -> *(pointer to function) -> function
*(pf) -> *(pointer to function) -> function
*(*pf) -> *(function) -> *(pointer to function) -> function

And further:

*(*(&f)) -> *(function) -> *(pointer to function) -> function
*(*(f)) -> *(function) -> *(pointer to function) -> function
*(*(pf)) -> *(function) -> *(pointer to function) -> function
*(*(*pf)) -> *(function) -> *(pointer to function) -> function

etc.

So you can pretty much replace any function() with a (******function)()
and it's the same thing.

The array you have is just an extra layer of complexity.

Jarno A Wuolijoki
Guest
 
Posts: n/a
#3: Nov 13 '05

re: Array of function pointers


On Thu, 4 Dec 2003, Jarno A Wuolijoki wrote:
[color=blue]
> Now, like arrays, functions usually decay to pointers to them:[/color]

Oh, let's fix an "implied" thinko before anyone else catches:

Arrays will of course decay to pointers to their elements, not
to pointers to itself.

Closed Thread