receiving function pointers and storing them in variables in standard c

I would like to have a function called "get_example_by_id" which takes in an int l and "returns" int a, b and two function pointers f and J. My initial take would be:

int a, b;
double (*f) (double), (*J) (double, double);
get_example_by_id(l, &a, &b, &f, &J);

Later on, I need f and J to be callable, since I need to them to make calculations.
Right now, when I try to call

double f1(double t);
double F1(double t, double alpha);

void get_example_by_id(int l, int *a, int *b, double (*f) (double), double (*F) (double, double)) {
    
    switch(l) {
        case 1:
            *a = 0; *b = 5; f = f1; F = F1;
        default:
            break;
    }
}


double f1(double t) {
    return t;
}

double F1(double t, double alpha) {
    return 1/tgamma(alpha + 2) * powl(t, alpha + 2);
}

(get_example_by_id is defined above in not here shown section) f(1) is NULL and therefore not callable. Additionally I get this error "undefined Symbol _f and _F" since experimenting which I don’t know how to resolve. Any help is appreciated even new ideas about how to code this.

P.S. there are more functions to come and this is supposed to become some kind of database

EDIT: Working example would be printf("%f", f(1)) after get_example_by_id() call, so that I can be sure the function call is actually performed right.

EDIT2: fixed actually function pointer declaration. Problem is now (as before) Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) when executing where f = NULL

>Solution :

It is not a function pointer. To declare function pointers you need to use different syntax.

double (*f)(double), (*J)(double, double);

To modify the pointer you need to pass reference to it:

double f1(double t);
double F1(double t, double alpha);

void get_example_by_id(int l, int *a, int *b, double (**f) (double), double (**F) (double, double)) {
    
    switch(l) {
        case 1:
            *a = 0; *b = 5; *f = f1; *F = F1;
        default:
            break;
    }
}


double f1(double t) {
    printf("It is f1\n");
    return 1.1;
}

double F1(double t, double alpha) {
    printf("It is F1\n");
    return 0.0;
}

int main(void)
{
    double (*f)(double), (*J)(double, double);
    get_example_by_id(1, &(int){0}, &(int){0}, &f, &J);
    f(0.);
    J(0.,0.);
}

https://godbolt.org/z/oTndWeze9

Leave a Reply