0

I have an array of 6 function pointers:

int (*arrayOfFunPointers[6])();


What I want to do now, is to allocate that array in heap
Because I create the array in a function and return a pointer to that array:

int (*(*fun2())[6])(){

    int (*funPointer)();
    int (*arrayOfFunPointers[6])();
    int (*(*pointerToArrayOfFunPointers)[6])();

    funPointer = &fun;
    arrayOfFunPointers[0] = funPointer;
    pointerToArrayOfFunPointers = &arrayOfFunPointers;

    return pointerToArrayOfFunPointers;
}

Outside of the method, the arrayOfFunPointers lose his validity area and the returned pointer point to "nothing"

I tried a lot like:

int (*arrayOfFunPointers[6])() = new int (*[6])();

or with typedef:

typedef int (*arrayOfFunPointers[6])();
arrayOfFunPointerss *array = new arrayOfFunPointers;

or by assignment to the returned pointer:

pointerToArrayOfFunPointers = new arrayOfFunPointers;
pointerToArrayOfFunPointers = new arrayOfFunPointers[]; //or

But nothing works.

Maybe I do not understand the use of the keyword new correctly, then it would be very helpful if anyone could tell me where I make a thinking mistake

Can anyone help me please? That would be nice

1
  • Even if you succeed in getting a pointer to an array of pointers to functions (gasp!), any attempts to call one of those functions will look just horrible, perhaps (*((*ptr)[i]))();, so why bother? Go with YSC's simplification instead. Commented Feb 16, 2018 at 13:50

1 Answer 1

3

You can simplify your life with tools from C++11. What about:

std::array<FunPointer, 6> getFunctions()
{
    std::array<FunPointer, 6> result;
    // ...
    return result;
}

isn't it just nice? Ne need to bother with dynamic memory, just copy those 6 pointers around, it is relatively cheap.

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

2 Comments

Thanks for your quick reply! I will try it out. Is FunPointer a typedef?
It works, thanks. But the question was more: Can I do it and not can I simplify it. Please excuse if the question was inaccurate.

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.