Array of function pointers

S

sushil

+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.
 
J

Jarno A Wuolijoki

+19 (A_HANDLER[0])();
+20 (*A_HANDLER[1])();
^ Is this '*' required ?

Not really, but it doesn't harm either.

I could not understand why there is no error due to '*' at line no. 20.
Could anybody help me ?

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.
 
J

Jarno A Wuolijoki

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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top