Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array of functions dynamically?

What if i want to have an array of pointers to a function and the size of the array is not known from the beginning? I'm just curious if there's a way to do that. Using new statement or maybe something else. Something looking similar to

void (* testArray[5])(void *) = new void ()(void *);
like image 889
Andrey Chernukha Avatar asked Apr 02 '12 19:04

Andrey Chernukha


3 Answers

You could use a 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 it using the FunPointer i defined in the snippet above:

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

Though i would still go for the vector solution, taking into account that you don't know the size of the array during compilation time and that you are using C++ and not C.

like image 161
mfontanini Avatar answered Sep 30 '22 17:09

mfontanini


With typedef, the new expression is trivial:

typedef void(*F)(void*);

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

Without typedef, it is somewhat more difficult:

void x(void*) {}
int main () {
  void (*(*testArray))(void*) = new (void(*[5])(void*));
  testArray[3] = x;

  if(testArray[3]) testArray[3](0);
}
like image 43
Robᵩ Avatar answered Sep 30 '22 16:09

Robᵩ


for(i=0;i<length;i++)
A[i]=new node

or

#include <vector>

std::vector<someObj*> x;
x.resize(someSize);
like image 32
Har Avatar answered Sep 30 '22 18:09

Har