0

My problem is: I want to write a program which create an array function pointers. I know how to make pointer to function, but don't know how to make array of them.

This is what I tried up to now:

double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a/b; }

int main() {
    double(*Padd)(double a, double b);
    double(*Psub)(double a, double b);
    double(*Pmult)(double a, double b);
    double(*Pdiv)(double a, double b);

    Padd = &add;
    Psub = ⊂
    Pmult = &mult;
    Pdiv = ÷
} 

In my code I create these pointers to functions in an array like e.g.

double Tpointers[3];
Tpointers[0] = Padd;
Tpointers[1] = Psub;
Tpointers[2] = Pmult;
Tpointers[3] = Pdiv;

How do I do this?

6
  • 2
    What is this indicator board supposed to do? Your question is needs alot more explaining. Preferably by an example in code. Commented Mar 18, 2018 at 10:03
  • 1
    What is an "indicator board"? Please use the correct English translation. Commented Mar 18, 2018 at 11:18
  • Array pointers. Commented Mar 18, 2018 at 11:42
  • 1
    Check out std::function. But the bigger question is: Why do you want to do this?. What do you want to reach in the end? Commented Mar 18, 2018 at 11:59
  • 1
    I think you are trying to create array of function pointers, please have a look at stackoverflow.com/questions/5488608/… it has answer for it Commented Mar 18, 2018 at 12:07

1 Answer 1

0

Simply declare a new type 'Tpointers' that represent a pointer to a function that give two double and return a double.

And in the code you can create an array of functions.

#include<iostream>

// The function pointer type!
typedef double (*Tpointers)(double, double);

double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a / b; }

int main() {
  // A functions pointers array .
  Tpointers fun_array[4];

  // Assign the values 
  fun_array[0] = &add;
  fun_array[1] = &sub;
  fun_array[2] = &mult;
  fun_array[3] = &div;

  // A little test
  std::cout << fun_array[2](3, 3) << " " << fun_array[3](3,3) << " " << fun_array[1](3,3)
        << std::endl;

  return 0;
}

In c++ you can also create an std::vector of functions pointer ... or any containers from the std libraries of "Tpointers".

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

Comments