将函数作为参数传递不起作用

Bur*_*rak 0 c parameters pointers function

我想将函数作为参数传递给另一个函数.我已经在谷歌上搜索过有关这方面的信息,我发现已经有了解释,但它对我不起作用,我不知道为什么.

我有以下代码:

void doSomething(uint64_t *);
Run Code Online (Sandbox Code Playgroud)

这是我想通过的功能.

int functionToCall(int x, int y, void (*f)(uint64_t *));
Run Code Online (Sandbox Code Playgroud)

这是我要调用的函数并传递doSomething()函数.

我的代码现在是:

uint64_t *state = malloc(sizeof(uint64_t) * 10);
void (*f)(uint64_t *) = doSomething;
functionToCall(2, 3, f(state));
Run Code Online (Sandbox Code Playgroud)

如果我现在编译上面的代码,我总是得到:

错误:无效使用void表达式

有什么问题?

HRo*_*old 5

该错误来自于您不传递指向函数的指针但函数的结果(无效).

如果在你的功能functionToCall你要调用doSomethingstate变量,那么你应该做这样的事情:

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);    
Run Code Online (Sandbox Code Playgroud)