1

I need to save in Arrays method pointers, something like this:

int main() {
void* man[10];
man[0]= void* hello();
man[0](2);


}

void hello(int val){

}

The question is, i can do that?

Thanks

2 Answers 2

3

Yes, you can easily achieve this by creating an array of function pointers. This is most readable if you alias the function type first:

void hello(int);
void world(int);

int main()
{
    using fn = void(int);
    fn * arr[] = { hello, world };
}

Usage:

fn[0](10);
fn[1](20);

Without a separate alias the syntax is a little hairer:

void (*arr[])(int) = { hello, world };

Or:

void (*arr[2])(int);
arr[0] = hello;
arr[1] = world;
Sign up to request clarification or add additional context in comments.

2 Comments

using... it's probably going to be a few more years before I remember I can do that.
@user4581301 You'd better learn it! It's incredibly helpful. :)
0

Yes you can, but may I recommend std::function? It handles more complex cases, such as pointers to class methods, much more easily.

Here's an example of both the function pointer way and the std::function way:

#include <iostream>
#include <functional> // for std::function

//typedef void (*funcp)(int); // define a type. This makes everything else way, way easier.
//The above is obsolete syntax.
using funcp = void(*)(int); // Welcome to 2011, monkeyboy. You're five years late


void hello(int val) // put the function up ahead of the usage so main can see it.
{
    std::cout << val << std::endl;
}


int main()
{
    funcp man[10]; 
    man[0]= hello;
    man[0](2);

    std::function<void(int)> man2[10]; // no need for typdef. Template takes care of it
    man2[0] = hello;
    man2[0](3);

}

2 Comments

typedef is really obsolete in C++. using is a more powerful and more readable alternative.
Just berated myself above for not using it.

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.