[英]Passing a function with array its parameter as a parameter to another function in C
我正在尝试计算给定方程的雅可比矩阵(数值,在给定点)。 现在,我事先不知道方程的维数,所以我不能只做类似的事情
static double f(double x1, x2)
{
return x1 * x1 - 2 * x1 * x2;
}
所以相反,我将输入值作为一个数组获取,就像这样
static double f(double xArray[])
{
return xArray[0] * xArray[0] - 2 * xArray[1] * xArray[0];
}
void jacobian(double xArray[], double jacob_matrix, size_t size,
double f(double xArray[], size_t))
{
// calculations
}
但是,当我尝试从main
调用 function 时
int main(void)
{
double x_input[4] = {1., 1., 3., 4.};
double jacob_matrix[4];
jacobian(x_input, jacob_matrix, 4, f(x_input, 4));
return 0;
}
我得到incompatible type for argument 4 of 'jacobian'
我想这与我的数组被转换为指针有关,但我不知道如何解决这个问题。
您需要将 function 指针传递给f
,而不是调用f
的结果。 尝试:
jacobian(x_input, jacob_matrix, 4, f);
对于 function 签名:
void jacobian(double xArray[], double jacob_matrix, size_t size,
double f(double xArray[], size_t))
对于第二个参数,如果你要传递一个数组,你需要参数是一个指针, double* jacob_matrix
或double jacob_matrix[]
。
For the 4th argument, the passed function arguments should match the caller signature, so in your case you are passing a function which is of type double (*)(double *)
, but the caller expects a function of type double (*)(double *, size_t)
,因此应更改其中一个以匹配,或者向被调用的 function 添加第二个参数,或者删除调用者 function 签名的第二个参数。
对于后者的示例,删除大小参数,function 签名应该是:
void jacobian(double xArray[], double* jacob_matrix, size_t size,
double f(double xArray[]))
然后你可以调用:
jacobian(x_input, jacob_matrix, 4, f);
您还可以向调用的 function 添加第二个参数:
static double f(double xArray[], size_t size)
对于这种情况,您不需要更改调用方 function 签名中的任何内容,但您仍然必须按照上图所示进行调用。
请注意,这些注释涉及代码的语言正确性,而不是数学部分,即雅可比计算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.