Home > OS >  Passing a function with array its parameter as a parameter to another function in C
Passing a function with array its parameter as a parameter to another function in C

Time:01-03

I am trying to calculate the Jacobian matrix (numerical, at a given point) of a given equation. Now, I don't know the dimension of the equation beforehand, so I can't just do something like

static double f(double x1, x2)
{
    return x1 * x1 - 2 * x1 * x2;
}

so instead, I am getting the input values as an array like so


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
}

However, when I try to call the function from main like

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;
}

I get incompatible type for argument 4 of 'jacobian' I imagine this has to do with my array being casted into a pointer, but I can't figure out how to fix this.

CodePudding user response:

You need to pass the function pointer to f, not the result of calling f. Try:

jacobian(x_input, jacob_matrix, 4, f);

CodePudding user response:

For the function signature:

void jacobian(double xArray[], double jacob_matrix, size_t size,
    double f(double xArray[], size_t)) 

For the second argument, if you're going to pass an array you need the argument to be a pointer, double* jacob_matrix or 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), so one of them should be changed to match, either add a second argument to the called function, or remove the second argument of the caller function signature.

For an example of the latter, removing the size argument, the function signature should be:

void jacobian(double xArray[], double* jacob_matrix, size_t size,
    double f(double xArray[])) 

Then you can call:

jacobian(x_input, jacob_matrix, 4, f);

You can also add a second argument to the called function:

static double f(double xArray[], size_t size) 

For this case you don't need to change anything in the caller function signature, but you still must make the call as shown above.

Note that these remarks address the language correctness of the code, not the mathematical part, i.e. the jacobian calculation.

  • Related