简体   繁体   中英

Pass function with 2D array input to a function

I want to pass a function to a function, in which case the passing function has 2D arrays for input.

For 1D arrays I have done like that:

void bungee(double Y[], double DY[])
{
   // ...
}

void euler(void(ODES)(double[], double[]), double A[], double STEP)
{
   // ...

   ODES(A, B);
}

int main()
{
    // ...

    euler(bungee, y, dt);

    return 0;
}

Now I would like to pass bungee to euler with 2D arrays input, like this:

void bungee(double Y[][], double DY[][])
{ // ... }

void euler(void(ODES)(double[][], double[][])/*,...*/)
{ // ... }

int main()
{ 
    euler(bungee);
    return 0;
}

in C/C++, arrays will be converted to pointer when passing to function. double Y[] will be same as double *Y.

For two dimentional arrays, you must provide the inner dimension when passing to function.

Because if you pass double Y[][], it will be converted to double (*Y)[], which is an incomplete type.

Instead, double Y[][50], will be converted to double (*Y)[50], which is fine.

For N dimentional array, you must provide the inner N-1 dimensions.

For example, double Y[][10][20][30].

Like user534498 explained for continuous arrays, eg

void bungee(double [][50]);

void main()
{
    double array[100][50];
    bungee(array);
}

but if you create your 2D arrays like this

double **arr = new double* [100];
for (int i=0; i<100; i++)
    arr[i] = new double [50];

you must use

void bungee(double **);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM