-4

I know how to send a pointer to a function, but how can I send correctly a pointer to function to function?

Code:

#include <iostream>
#include <ctime>
using namespace std;

int avg(int *A, int *B, int A_size, int B_size) {
    return NULL;
}
int min(int *A, int *B, int A_size, int B_size) {
    return NULL;
}
int max(int *A, int *B, int A_size, int B_size) {
    return NULL;
}
int Action(int *A, int *B, int A_size, int B_size, int (*fun_ptr)) {
    return NULL;
}

void main() {
    srand(time(NULL));
    int A_size, B_size; 
    int (*f) (int*, int*, int, int);
    cout << "Type A size and B size: "; cin >> A_size >> B_size;
    int *A = new int[A_size];
    int *B = new int[B_size];
    cout << "A massive: ";
    for (int *i = A; i < A + A_size; i++) {
        *i = rand() % 10;
        cout << *i << " ";
    }
    cout << endl;
    cout << "B massive: ";
    for (int *i = B; i < B + B_size; i++) {
        *i = rand() % 10;
        cout << *i << " ";
    }
    cout << endl;
    int choose;
    cout << "1.max" << endl;
    cout << "2.min" << endl;
    cout << "3.avg" << endl;
    cout << "Chose the fucntion: ";  cin >> choose;
    switch (choose) {
        case 1: f = &max; break;
        case 2: f = &min; break;
        case 3: f = &avg; break;
    }
    Action(&A[0], &B[0], A_size, B_size, &f);
}

I want to send pointer to function to function Action, but what do I need to change? It is not working. f is the pointer to function.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Ur_Sok
  • 17
  • 8

1 Answers1

1

int (*fun_ptr) is equivalent to int *fun_ptr. It declares a pointer to int, not to a function.

This is the syntax for declaring a function pointer (in particular, a function pointer that can point to avg, min or max): int (*fun_ptr)(int*, int*, int, int). Note the argument list that was missing from your declaration. PS. You had already managed to do this when you declared f.


Other bugs in the code:

main must return int. NULL is not guaranteed to be implicitly convertible to int. The type of &f is a pointer to a pointer to a function, not a pointer to a function.

eerorika
  • 223,800
  • 12
  • 181
  • 301