2

I want to know, how to create a pointer that points to the address of a function.

Supose that we have the following function:

int doublex(int a)
{
    return a*2;
}

I already know that & is used to get the address. How could I point to this function?

Grandtour
  • 1,127
  • 1
  • 11
  • 28

3 Answers3

3

As said, you can just take the address with the & operator. Then the easiest way is to assign it with a auto variable to store it, now you can use your variable like a function itself.

int doubleNumber(int x)
{
    return x*2;
}

int main()
{
  auto func = &doubleNumber;
  std::cout << func(3);
}

See a live example here

Moia
  • 2,216
  • 1
  • 12
  • 34
  • 1
    This is right, but in my case, the pointer was declared using "malloc" – Grandtour Dec 15 '18 at 17:21
  • and what's your point? You should give a more precise context of what you're asking – Moia Dec 15 '18 at 17:24
  • That's because I'm always confused in how to use malloc, so I didn't put the declaration of the pointer in my answer. – Grandtour Dec 15 '18 at 17:25
  • 1
    @Grandtour begin with not using malloc if you're writing C++. – Moia Dec 15 '18 at 17:27
  • Oh, yes, I tought that I was still programming C, thanks for reminding me. – Grandtour Dec 15 '18 at 17:28
  • Can you explain what is the "auto" type in your answer? This is only the remaining thing to I accept your answer. – Grandtour Dec 15 '18 at 17:32
  • It's quite OT, but anyway. **auto specifier**: _For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer._ https://en.cppreference.com/w/cpp/language/auto – Moia Dec 15 '18 at 17:36
  • To do this in C, is it the same way? – Grandtour Dec 15 '18 at 17:44
  • @Grandtour auto here is deduced as (an unconfortable) `int (*)(int) func;` so the same as a C function pointer. see here https://cppinsights.io/ – Moia Sep 11 '19 at 13:00
2

Just do:

auto function_pointer = &doublex;

And what is the auto type?

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime. Source here

This will help you: C++ auto keyword. Why is it magic?

IncredibleCoding
  • 191
  • 2
  • 14
0

You can do something like this and store references to compatible functions or pass your function as parameter in another function.

typedef int (*my_function_type)(int a);
int double_number(int a)
{
    return a*2;
}
my_function_type my_function_pointer = double_number;
int transform_number(int target, my_function_type transform_function) {
    return transform_function(target);
}

I hope it helps you

Givi
  • 79
  • 4