如何通过传递指针来调用具有参数类型的高维数组的函数
How to call a function with a parameter typed high-dimensional array by passing a pointer?
例如,我有一个类似(需要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);
现在,你有两种可能性:
将C用于多维数组。
请使用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
类。
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法