首页 > 解决方案 > C使用函数而不调用其参数

问题描述

我正在使用一些遗留的 C 代码,这些代码非常复杂。这是我所拥有的:

在头文件中声明:

int derivs(double,const double *,double *,void *);

然后在同名的 .c 文件中是另一个声明:

int derivs(double,const double *,double *,void *);

然后定义函数(在同一个文件中):

int derivs(double t, const double y[], double dydN[], void * params)
{
     int i;

    if(y[2]>=1.0)
    {
        for(i=0;i<NEQS;i++)
        {
            dydN[i] = 0.0;
        }
    }
    else
    {
        if(y[2] > VERYSMALLNUM)/*Here for numerical issues in
                        sqrt()*/
        {
            dydN[0]= - sqrt(y[2]/FOURPI); //d phi/ d N eq. (17)
        }
        else
        {
            dydN[0] = 0.0;
        }
        dydN[1] = y[1]*y[2]; // dH / dN = eps * H
        dydN[2] = y[2]*(y[3]+2.0*y[2]); // d epsilon / dN
        dydN[3] = 2.0*y[4]-5.0*y[2]*y[3]-12.0*y[2]*y[2];

        for(i=4;i<NEQS-1;i++)
        {
            dydN[i] = (0.5*(i-3)*y[3]+(i-4)*y[2])*y[i]+y[i+1];
        }
        dydN[NEQS-1] = (0.5*(NEQS-4)*y[3]+(NEQS-5)*y[2])*y[NEQS-1];

    }
    return GSL_SUCCESS;
}

然后在同一文件中的另一个函数中是以下行:

z=int_de(y,Nstart,Nend,&kount,kmax,yp,xp,NEQS,derivs);

即,derivs 仅按名称调用,没有任何参数。函数 int_de 声明如下:

int int_de (gsl_vector *y, double N, double Nend, int *kount, int kmax,
gsl_matrix *ypp, gsl_vector *xpp, int NEQS, int (*derivs)(double,const
double *, double *,void *))

我的问题是如何使用derivsinint_de工作?它在没有任何参数的情况下被调用。

标签: c

解决方案


答案是该函数derivs还没有被调用——它的地址被传递给int_de,稍后可能会derivs使用它的地址调用。参见例如https://www.geeksforgeeks.org/function-pointer-in-c/

这是一个如何有用的例子。在下面的代码中,我们重新使用函数中的逻辑accumulate来获取 int 列表的 thesum或 the product,具体取决于我们传入的addand multiply。这样,我们不必写出两次循环逻辑,这应该有助于保护我们免受任何复制粘贴错误。

#include <stdio.h>

int add(int x, int y)
{
    return x + y;
}

int multiply(int x, int y)
{
    return x * y;
}

// We can pass any function with matching signature in as binary_operation, and
// accumulate will use it!
int accumulate(int starting_value, int length, int* values, int binary_operation(int, int))
{
    int result = starting_value;
    for (int index = 0; index < length; index++)
    {
        result = binary_operation(result, values[index]);
    }
    return result;
}

int sum(int length, int* values)
{
    return accumulate(0, length, values, add);
}

int product(int length, int* values)
{
    return accumulate(1, length, values, multiply);
}

int main(int argc, char** argv)
{
    int values[5] = { 1, 2, 3, 4, 5 };
    printf("sum of first three = %d\n", sum(3, values));
    printf("product of all five = %d\n", product(5, values));
}

编译并运行它,我得到输出:

sum of first three = 6
product of all five = 120

推荐阅读