Pointer to a function used in arithmetic

Hello everybody. First post here. Wonder if you could help me with this warning: pointer to a function used in arithmetic. When I'm running the program it crashes.

The problematic line seems to be this one: res[i] = (pf[i])(a, b);

And here's the full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Exercise 7.10.cpp

#include <iostream>
void Calculate(double a, double b, double (*pf)(double, double), double res[]);
double Add(double x, double y);
double Subtract(double x, double y);
double Multiply(double x, double y);
double Divide(double x, double y);

int main()
{
    using std::cout;
    using std::cin;
    double (*pfu[4])(double, double) {Add, Subtract, Multiply, Divide};
    double first, second;
    double result[4];
    cout << "Please, enter the first number (q to quit): ";
    cin >> first;
    cout << "\nPlease, enter the second number (q to quit): ";
    cin >> second;
    Calculate(first, second, pfu[0], result);
    cout << "\nHere are the results of: \n"
            "Adding them: " << result[0]
         << "\nSubtracting them: " << result[1]
         << "\nMultiplying them: " << result[2]
         << "\nDividing them: " << result[3];
    return 0;
}

void Calculate(double a, double b, double (*pf)(double, double), double res[])
{
    for (int i = 0; i < 4; i++)
        res[i] = (pf[i])(a, b); // Assign the value of each calculating function to each element of the array res.
}

double Add(double x, double y)
{
    return x + y;
}

double Subtract(double x, double y)
{
    return x - y;
}

double Multiply(double x, double y)
{
    return x * y;
}

double Divide(double x, double y)
{
    return x / y;


I just don't get what can be wrong. Any help?
You pass a single function pointer to the function when you want to pass a pointer to the first element in the array (pointer to function pointer).

void Calculate(double a, double b, double (**pf)(double, double), double res[])
or if you prefer the array syntax:
void Calculate(double a, double b, double (*pf[])(double, double), double res[])

Calculate(first, second, pfu, result);
Last edited on
Oops, thank you very much. That solved my problem! Beginner's mistake. :P
That is one thing I forget about, so I just always do int main(int argc, char** argv) in every code now.
Topic archived. No new replies allowed.