Reputation: 353
I want to pass a function as argument to another function. I searched already Google about information on this and I found already a explanation but it doesn't work for me and I don't know why.
I have following code:
void doSomething(uint64_t *);
This is my function I want to pass.
int functionToCall(int x, int y, void (*f)(uint64_t *));
This is my function I want to call and pass the doSomething() function.
In my code now is:
uint64_t *state = malloc(sizeof(uint64_t) * 10);
void (*f)(uint64_t *) = doSomething;
functionToCall(2, 3, f(state));
If I compile the above code now I get always:
error: invalid use of void expression
What is the problem with that?
Upvotes: 0
Views: 107
Reputation: 85
I'm not that good in C but i guess that you could get some help from previous similar post
How do you pass a function as a parameter in C?
Hope that my answer helped
Upvotes: -1
Reputation: 229
The error come from the fact that you dont pass a pointer to the function but the function's result (which is void).
If in your function functionToCall
you want to call doSomething
with the state
variable, then you should do something like this:
void doSomething(uint64_t *);
int functionToCall(int x, int y, unint64_t * state, void (*f)(uint64_t *))
{
f(state);
/* ... */
}
uint64_t *state = malloc(sizeof(uint64_t) * 10);
void (*f)(uint64_t *) = doSomething;
functionToCall(2, 3, state, f);
Upvotes: 5
Reputation: 353
I did not realize that I have passed the argument for the doSomething()
function in my functionToCall
function.
So, the line,
functionToCall(2, 3, f(state));
Has to be,
functionToCall(2, 3, f);
Upvotes: 1