How to create an array of functions dynamically?

What if I want to have an array of function pointers and the size of the array is unknown from the start? I'm just wondering if there is a way to do this. Use a new statement or perhaps something else. Something like

void (* testArray[5])(void *) = new void ()(void *); 
+6
source share
3 answers

You can use std::vector :

 #include <vector> typedef void (*FunPointer)(void *); std::vector<FunPointer> pointers; 

If you really want to use a static array, it would be better to do this using FunPointer i, defined in the snippet above:

 FunPointer testArray[5]; testArray[0] = some_fun_pointer; 

Although I’ll still go for a vector solution, given that you don’t know the size of the array at compile time and that you use C ++, not C.

+8
source

With typedef new expression is trivial:

 typedef void(*F)(void*); int main () { F *testArray = new F[5]; if(testArray[0]) testArray[0](0); } 

Without a typedef , this is somewhat more complicated:

 void x(void*) {} int main () { void (*(*testArray))(void*) = new (void(*[5])(void*)); testArray[3] = x; if(testArray[3]) testArray[3](0); } 
+5
source
 for(i=0;i<length;i++) A[i]=new node 

or

 #include <vector> std::vector<someObj*> x; x.resize(someSize); 
+1
source

Source: https://habr.com/ru/post/912256/


All Articles