我正在尝试制作一个用一些随机值填充二次矩阵的程序。所以这里是源代码(工作正常):
#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main()
{
int const n = 5;
int matrix[n][n];
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
matrix[i][j] = rand()%10; // fill matrix
cout<<setw(2)<<matrix[i][j]; // matrix output
}
cout<<"\n"; // new line
}
}
但现在我想用我自己的函数重写这段代码:
#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
void fillAndPrintArray (int **matrix, int n); // function prototype
int main()
{
int const n = 5;
int matrix[n][n];
fillAndPrintArray(matrix, n);
}
void fillAndPrintArray(int **matrix, int n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
matrix[i][j] = rand()%10; // fill matrix
cout<<setw(2)<<matrix[i][j];
}
cout<<"\n"; // new line
}
}
但是我无法编译这段代码。我收到错误:
||In function 'int main()':error: cannot convert 'int (*)[5]' to 'int**' for argument '1' to 'void fillAndPrintArray(int**, int)'.
我不知道如何解决这个问题。
最佳答案
问题是您将一个多维数组传递给一个函数,该函数接受一个指向指针的指针。对于数组,这是指向指针数组第一个元素的指针,而不是二维数组。
如果您想将多维数组传递给函数,您可以使用模板函数并通过引用获取数组。
template<std::size_t U, std::size_t V>
void func(const int (&arr)[U][V])
{
// do stuff
}
int main()
{
int arr1[10][10];
int arr2[15][10];
func(arr1);
func(arr2);
}
要在没有模板函数的情况下执行此操作,只需将 U
和 V
替换为所需的尺寸即可。例如,在您的问题中传递一个 5x5 数组,您会这样做。
void func(const int(&arr)[5][5])
{
}
关于c++ - 如何将二维数组传递给函数以便代码可以编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663494/