如何将多维指针数组传递给函数
How to pass a multidimensional array of pointers to a function?
我有一个函数:
void ord_matrix_multiplication(Cache& cache, Block* block1[][], Block* block2[][], Block* block3[][], int A[][], int B[][], int C[][], int i, int j, int k, int n, int s)
我在调用函数中有以下代码:
int A[n][n];
Block* blocks1[n][n];
int B[n][n];
Block* blocks2[n][n];
int C[n][n];
Block* blocks3[n][n];
...
//some code
...
ord_matrix_multiplication(cache, blocks1, blocks2, blocks3, A, B, C, i, j, k, n, s);
但我得到以下错误:
cacheaware.cpp:35: error: declaration of ‘block1’ as multidimensional array must have bounds for all dimensions except the first
cacheaware.cpp:35: error: expected ‘)’ before ‘,’ token
cacheaware.cpp:35: error: expected initializer before ‘*’ token
然后我将函数dclaration更改为:
void ord_matrix_multiplication(Cache& cache, Block* block1[][100], Block* block2[][100], Block* block3[][100], int A[][100], int B[][100], int C[][100], int i, int j, int k, int n, int s)
这样做,我得到:
cannot convert ‘Block* (*)[(((unsigned int)(((int)n) + -0x00000000000000001)) + 1)]’ to ‘Block* (*)[100]’ for argument ‘2’ to ‘void ord_matrix_multiplication(Cache&, Block* (*)[100], Block* (*)[100], Block* (*)[100], int (*)[100], int (*)[100], int (*)[100], int, int, int, int, int)’
有人能告诉我如何解决这个问题吗?
多维数组不是在C++中管理的,您必须将函数声明为:
void ord_matrix_multiplication(Cache& cache, Block* block1, Block* block2, Block* block3, int* A, int* B, int* C, int i, int j, int k, int n, int s)
此后,您可以以多维方式对这些数组进行索引,尽管您要负责数据完整性和绑定检查。
此外,能够声明可变大小的数组并不是标准C++。数组的sise必须在声明时已知,或者在初始化函数中使用"new"关键字进行分配。
我以前遇到过这样的问题。最简单的解决方案是使用指针
int* x; // x can be pointer to int or pointer to the first item in the array
int** y; // y can be a pointer to pointer of int or a pointer to array of int or 2 dimension array
int x*** z; // z can be used as three dimensional array
您还可以让您的函数将指针指向任何类型的void*,并将其强制转换为您确信会将其传递给的类型
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中