我读过函数指针的语法,但我不能在我的代码中使用.
This video解释说,语法是:
type func0(type0 arg0, ..., typen argn){
// do something
return a_thing;
}
则用于在另一个函数中传递函数指针的是:
type func1((*func0)(type0 arg0, ..., typen argn), another args){
//do something
func0(arg0, ..., argn);
return a_thing;
}
但后来,我读到了第一个答案,大约是How do function pointers in C work?,语法是:
type func1((*func0)(type0 arg0, ..., typen argn), another args) {
//do something
(*func0)(arg0, ..., argn);
return a_thing;
}
这是有意义的,因为您正在取消引用您正在传递的指针.最后,C function pointers invocation syntax中的第一个答案解释语法可以是:
&func
func
*func
**func
我不知道哪个信息是正确的.我有代码:
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;
}
它抛出错误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);
}
正如你所看到的,所有的问题都是我输入了double *(operation)(double, double)
而不是double (*operation)(double, double)
.
感谢所有人的回答.我学到了很多,很抱歉我拼错了.