views:

149

answers:

5

How would I create an array of ten function pointers? What I have is a for loop, and I want to set a function pointer to a different function on each iteration. so:

//pseudocode
for i (0..10)
    function = array_of_functions[i];
//...
+4  A: 

This code:

return_t (*array_of_functions[10])(arg1_t, arg2_t);

Declares "array_of_functions" as a 10-element array of function pointers where each pointed-to function takes two arguments of type arg1_t and arg2_t and returns type return_t. Replace types and adjust the number of arguments as appropriate.

Tyler McHenry
+8  A: 
// Define alias for function pointer type for convenience
typedef void (*action)(int);

// Example function
void print(int) { ... }

action fs[10] = { print, ... };
for (int i = 0; i < 10; ++i)
{
    action f = fs[i];

    // Call it somehow
    f(i * i);
}
Pavel Minaev
+2  A: 
Michael Aaron Safyan
+2  A: 

Any time you have to deal with ugly function pointer syntax it's better to use a typedef.

#include <iostream>

void a(int i)
{
    std::cout<<"a: "<<i<<std::endl;
}

void b(int i)
{
    std::cout<<"b: "<<i<<std::endl;
}

typedef void (*fn)(int);

int main(int argc, char**argv)
{

    fn foo[2];


    foo[0] = a;
    foo[1] = b;


    for(size_t i = 0; i < sizeof(foo) / sizeof(foo[0]); ++i)
    {
     foo[i](i);
    }

    return 0;
}
Brian R. Bondy
+1  A: 
T (*array_of_functions[10])();

Where T is the return type of each function (all functions return the same type, naturally). Things get tricky if you want to store pointers to functions with different numbers/types of parameters:

int foo(void) {...}
int bar(int x) {...}
int bletch(double y, double z) {...}
...
int (*array_of_functions[10])() = {foo, bar, bletch, ...};

If so, you'll have to keep track of what number and types of parameters each function requires somehow so you can call it correctly.

I'm actually kind of down on typedefs for function pointer types; they tend to obscure as much as they simplify.

John Bode