如何将多维指针数组传递给函数

How to pass a multidimensional array of pointers to a function?

本文关键字:函数 数组 指针      更新时间:2023-10-16

我有一个函数:

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*,并将其强制转换为您确信会将其传递给的类型