Dan*_*ñoz 5 c function-pointers
我已经阅读了有关函数指针语法的内容,但无法在我的代码中工作。
该视频解释了语法是:
type func0(type0 arg0, ..., typen argn){
// do something
return a_thing;
}
Run Code Online (Sandbox Code Playgroud)
然后在另一个函数中传递函数指针是:
type func1((*func0)(type0 arg0, ..., typen argn), another args){
//do something
func0(arg0, ..., argn);
return a_thing;
}
Run Code Online (Sandbox Code Playgroud)
但是后来,我读了第一个关于C 中的函数指针如何工作?,语法为:
type func1((*func0)(type0 arg0, ..., typen argn), another args) {
//do something
(*func0)(arg0, ..., argn);
return a_thing;
}
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为您正在取消引用您正在传递的指针。最后, C 函数指针调用语法中的第一个答案解释了该语法可以是:
&func
func
*func
**func
Run Code Online (Sandbox Code Playgroud)
我不明白哪些信息是正确的。我有代码:
double *func1((*func0)(double), double *var) {
double *temp = malloc(some_size);
for(int i = 0; i < some_cycles; ++i) {
temp[i] = (*func0)(var[i]);
}
return temp;
}
Run Code Online (Sandbox Code Playgroud)
它会抛出错误a value of type "double *" cannot be assigned to an entity of type "double"
编辑:
对于任何想查看真实代码的人来说,是:
tensor_t *applyBinOpTensor(double *(operation)(double, double), tensor_t *tensor, double operand){
size_t total_size = indiceProduct(*tensor->shape);
double *values = malloc(total_size * sizeof(*values));
for(size_t i = 0; i < total_size; ++i){
values[i] = (*operation)(tensor->values[i], operand);
}
return initializeTensor(values, tensor->shape);
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,所有的问题都是我输入的double *(operation)(double, double)而不是double (*operation)(double, double).
感谢大家的回答。我学到了很多东西,对我的拼写错误感到抱歉。
将函数指针传递给函数相对容易。
给定一些函数指针:
int (*fptr) (int, double);
Run Code Online (Sandbox Code Playgroud)
只需将相同的语法压缩到参数列表中即可:
void some_func (int some_param, int (*fptr)(int, double), int some_other_param);
Run Code Online (Sandbox Code Playgroud)
当您尝试返回函数指针时,情况会变得更加混乱。让我们使用上面的函数并将函数指针从参数列表移动到返回类型:
int (*some_func(int some_param, int some_other_param)) (int, double);
Run Code Online (Sandbox Code Playgroud)
是的,看不懂的胡言乱语……
现在我们实际上可以从中学到什么?
始终使用 typedef。时期。
int (*fptr) (int, double);
Run Code Online (Sandbox Code Playgroud)