【问题标题】:How to pass two-dimensional array to the function so that code would compile如何将二维数组传递给函数以便代码编译
【发布时间】:2014-12-27 01:02:50
【问题描述】:

我正在尝试制作一个用一些随机值填充二次矩阵的程序。所以这里的源代码(工作正常):

#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)'.

我不知道如何解决这个问题。

【问题讨论】:

标签: c++ arrays function matrix


【解决方案1】:

问题是您将一个多维数组传递给一个函数,该函数接受一个指向指针的指针。对于数组,这是指向指针数组的第一个元素的指针,而不是二维数组。

如果要将多维数组传递给函数,可以使用模板函数并通过引用获取数组。

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])
{
}

【讨论】:

  • 我可以不使用模板吗?
  • @KiberPrestupnik 是的。尽管我认为没有理由不在此处使用模板,但已通过示例更新了答案,因为编译器会自动推断出数组大小的模板参数。
猜你喜欢
  • 2020-11-01
相关资源
最近更新 更多