Andrey Chernukha
Andrey Chernukha

Reputation: 21808

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 *);

Upvotes: 6

Views: 2018

Answers (3)

Robᵩ
Robᵩ

Reputation: 168626

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);
}

Upvotes: 5

mfontanini
mfontanini

Reputation: 21900

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.

Upvotes: 8

Har
Har

Reputation: 5004

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

or

#include <vector>

std::vector<someObj*> x;
x.resize(someSize);

Upvotes: 1

Related Questions