6

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

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

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

or

#include <vector>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.