Puzzling Programmer Puzzling Programmer - 20 days ago 6
C Question

How to retrieve a function from a function argument in C?

I'm stuck in getting a function pointer back from a function parameter.
Here's an example of what I'm trying to do.

int a(int I)
{
return I*I;
}

void get_a(int(*R)(int))
{
R = &a;
}

int main()
{
int(*function)(int) = NULL;

printf("function a=%p\n", a);

get_a(function);
printf("function a=%p\n", &function); // Is never the right address.

return 0;
}


Searching the net did not help, I could only find examples of pass a function as parameter, so I gave up and tried solving this problem by myself.

Answer

You have two issue here.

First, your function is modifying a local variable, so the result will never be reflected in the caller. You need to pass the address of your function pointer variable, then have get_a accept a pointer-to-function-pointer. By passing the variable's address, you can dereference it and modify it.

The second issue is that your second printf is printing the address of function instead of its value. Pass in the value.

void get_a(int(**R)(int))
{
    *R = &a;
}

int main()
{
    int(*function)(int) = NULL;

    printf("function a=%p\n", a);

    get_a(&function);
    printf("function a=%p\n", function);

    return 0;
}

Result:

function a=0x400498
function a=0x400498