How can I make an array of function pointer? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How can I make an array of function pointer?

I have five function and I want to call them from an array. How can I store the functions’ names in an array and instead of calling the name of each function, just bring the wanted index of array?

28th May 2020, 2:53 PM
Nika Soltani Tehrani
Nika Soltani Tehrani - avatar
5 Answers
+ 4
The type of a function pointer is just like the function declaration, but with "(*)" in place of the function name. So a pointer to: int foo( int ) would be: int (*)( int ) In order to name an instance of this type, put the name inside (*), after the star, so: int (*foo_ptr)( int ) declares a variable called foo_ptr that points to a function of this type. Arrays follow the normal C syntax of putting the brackets near the variable's identifier, so: int (*foo_ptr_array[2])( int ) declares a variable called foo_ptr_array which is an array of 2 function pointers. The syntax can get pretty messy, so it's often easier to make a typedef to the function pointer and then declare an array of those instead: Rock the code🤟🤟
28th May 2020, 3:05 PM
Piyush
Piyush - avatar
+ 4
typedef int (*foo_ptr_t)( int ); foo_ptr_t foo_ptr_array[2]; In either sample you can do things like: int f1( int ); int f2( int ); foo_ptr_array[0] = f1; foo_ptr_array[1] = f2; foo_ptr_array[0]( 1 ); Finally, you can dynamically allocate an array with either of: int (**a1)( int ) = calloc( 2, sizeof( int (*)( int ) ) ); foo_ptr_t * a2 = calloc( 2, sizeof( foo_ptr_t ) ); Notice the extra * in the first line to declare a1 as a pointer to the function pointer. This take a lot a time to write but this was my duty towards question. Just be go out of limits in coding. Rock the code🤟🤟
28th May 2020, 3:06 PM
Piyush
Piyush - avatar
+ 3
piyush singh Thank you a lot for spending your valuable time on my question 🙏🙏😊
28th May 2020, 6:10 PM
Nika Soltani Tehrani
Nika Soltani Tehrani - avatar
+ 1
Have a look at my profile, i've got some simple "array of functions" in there..... using typedef.
28th May 2020, 4:16 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Nika Soltani Tehrani no problem. Your most welcome
29th May 2020, 12:52 AM
Piyush
Piyush - avatar