Reputation: 25592
Arrays of function pointers can be created like so:
typedef void(*FunctionPointer)();
FunctionPointer functionPointers[] = {/* Stuff here */};
What is the syntax for creating a function pointer array without using the typedef
?
Upvotes: 69
Views: 64466
Reputation: 47
I've been building a game engine and have found that I needed dynamically allocated arrays of function pointers.
To address this simply, I've opted for encapsulating the function pointers inside a class.
Here's a simple example:
class Function{
private:
public:
int (*sampleFunction)(int);
};
static int returnInt(int val){
int ret = 20 * i;
return ret;
}
int main(void){
Function *functions; /* V put yours here V */
size_t functionCount = getFunctionCount();
functions = new Function[functionCount];
for(int i=0; i<functionCount; i++)
functions[i].sampleFunction = &returnInt;
for(int i=0; i<functionCount; i++)
functions[i].sampleFunction(i);
return 0;
}
Where can this be useful?
Say that you have a graphical application that you're building that creates buttons out of an undefined number of files in a directory.
Each button has a unique "hitbox" coordinate relative to it's position in an array, and you need to be able to uniquely handle a mouse click for each button.
The Functions class is meant to be placed inside another, more complex, class. Where the point of the function pointer is to make it easier to redefine the button click event when different algorithms are required for the same "form element".
Upvotes: 0
Reputation: 133014
arr //arr
arr [] //is an array (so index it)
* arr [] //of pointers (so dereference them)
(* arr [])() //to functions taking nothing (so call them with ())
void (* arr [])() //returning void
so your answer is
void (* arr [])() = {};
But naturally, this is a bad practice, just use typedefs
:)
Extra: Wonder how to declare an array of 3 pointers to functions taking int and returning a pointer to an array of 4 pointers to functions taking double and returning char? (how cool is that, huh? :))
arr //arr
arr [3] //is an array of 3 (index it)
* arr [3] //pointers
(* arr [3])(int) //to functions taking int (call it) and
*(* arr [3])(int) //returning a pointer (dereference it)
(*(* arr [3])(int))[4] //to an array of 4
*(*(* arr [3])(int))[4] //pointers
(*(*(* arr [3])(int))[4])(double) //to functions taking double and
char (*(*(* arr [3])(int))[4])(double) //returning char
:))
Upvotes: 130
Reputation: 40336
Remember "delcaration mimics use". So to use said array you'd say
(*FunctionPointers[0])();
Correct? Therefore to declare it, you use the same:
void (*FunctionPointers[])() = { ... };
Upvotes: 16
Reputation: 91270
Use this:
void (*FunctionPointers[])() = { };
Works like everything else, you place [] after the name.
Upvotes: 5