Reputation: 300
Let's say I have a function
int foo(void)
{
printf("Hello world");
}
And I want to use a pointer to a function to point to foo()
.
typedef int (*f_ptr)(void);
Which one of those cases would I use for that purpose?
(A) f_ptr my_ptr = foo;
my_ptr();
(B) f_ptr * my_ptr = foo;
my_ptr();
Now if I have 10 functions foo1(), foo2() .. foo10()
and I want to put them in an array and iterate through the array using a pointer to function, how would I do it?
f_ptr my_functions[10] =
{
foo1,
foo2,
..
foo10,
};
(A) f_ptr my_ptr = my_functions;
(B) f_ptr * my_ptr = my_functions;
for (int x = 0; x < 10; x++)
{
my_ptr();
my_ptr++;
}
Upvotes: 1
Views: 71
Reputation: 310980
For starters pay attention to that though this function
int foo(void)
{
printf("Hello world");
}
has the return type int
it returns nothing. Instead you could write for example
int foo(void)
{
return printf("Hello world");
}
Nevertheless an array designator used in expressions with rare exceptions is converted to pointer to its first element.
So if the element type of the array
f_ptr my_functions[10];
is f_ptr
then a pointer to elements of the array will look like
f_ptr * my_ptr = my_functions;
So for example you can write a loop using the pointer like
for ( size_t i = 0; i < 10; i++ )
{
my_ptr[i]();
}
Or
for ( f_ptr *my_ptr = my_functions; my_ptr != my_functions + 10; ++my_ptr )
{
( *my_ptr )();
}
Upvotes: 1