如何通过传递指针来调用具有参数类型的高维数组的函数

How to call a function with a parameter typed high-dimensional array by passing a pointer?

本文关键字:类型 参数 高维 函数 数组 何通过 指针 调用      更新时间:2023-10-16

例如,我有一个类似(需要c99)的函数

void fun(int nx, int ny, double a[nx][ny])
{
    // some code here
}

我有一个指针

double *p = new double[nx * ny];

并使用它来调用类似的函数

fun(nx, ny, p); // error for the type is not matched

怎么做?允许任何类型转换。

您想要的在C++中是不可能的,因为C++要求数组类型的大小是编译时常数。C99没有这个限制,所以函数声明

void fun(int nx, int ny, double a[nx][ny]);

是有效的C99,但不是有效的C++。顺便说一句,在C99中,该函数的正确调用如下所示:

int nx = ..., ny = ...;
double (*matrix)[ny] = malloc(nx*sizeof(*matrix));
fun(nx, ny, matrix);

现在,你有两种可能性:

  1. 将C用于多维数组。

  2. 请使用C++解决方法。


最简单的C++解决方法是vector<vector<double> >。这样就可以避免自己分配内存的麻烦,但是,2D矩阵中的行是不连续的。


您也可以使用这样的两层间接寻址:

double **matrix = new double*[nx];
for(int i = 0; i < ny; i++) matrix[i] = new double[ny];

并将您的功能声明为

void fun(int nx, int ny, double** a);

请注意,除了保存数据的数组之外,还需要一个额外的索引数组。然而,您可以自由使用单个大数组来保存数据:

double** matrix = new double*[nx];
double* storage = new double[nx*ny];
for(int i = 0; i < ny; i++) matrix[i] = &storage[ny*i];

最后一个可能的解决方法是,自己计算指数:

void fun(int nx, int ny, double* twoDArray) {
    //access the array with
    twoDArray[x*ny + y];
}
//somewhere else
double* matrix = new double[nx*ny];
fun(nx, ny, matrix);

这正是C99在顶部代码的情况下所做的,但类型检查要少得多。

试试这个:

void fun(int nx, int ny, double** a){
// some code here
// Get the element in this way: double myD = a[i][j];
}

总的来说:

double** a = new double*[nx];
for (int i = 0; i < nx; i++)
{
   a[i] = new double[ny];
}

并调用函数:

fun(nx, ny, a);

或者如果你想传递一个数组:

void fun(int nx, int ny, double* a){
int dim = nx*ny;
double myD = a[i];
}

否,不能将1d数组(或指向1d数组的指针)传递给声明为采用2d数组的函数。

如果你需要动态分配一个2d数组,你可以做的是:

// ny can be runtime variable in c99, but must be compile time constant in c++
constexpr int ny = 10;
int nx = 10;
double (*p)[ny]  = new double[nx][ny];
fun(nx, ny, p);

如果您想按原样使用1d数组,则需要修改fun以接受1d数组:

// note that double a[] or double* a param would be identical, nx*ny is just for documentation
void fun(int nx, int ny, double a[nx*ny])
     // access indices [i][j] like this: a[nx*j + i]

然而,在c++中,我建议您将任何动态分配隐藏在将管理内存的抽象后面。比如说,在这种情况下是Matrix类。