如何将未知大小的2维矩阵发送到函数

时间:2017-05-30 11:00:08

标签: c++ arrays function matrix multidimensional-array

我试图弄清楚如何将2维矩阵传递给函数

//function to print Matrix
void refl(int n, int board[][])
{
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {

            cout << board[i][j]  << "  ";
            }
        cout << endl; //printing the matrix to the screen
    }
}

int main()
{
    int n;
    string refl;
    cin>>n;
    int board[n][n]; //creates a n*n matrix or a 2d array.

        for(int i=0; i<n; i++)    //This loops on the rows.
    {
        for(int j=0; j<n; j++) //This loops on the columns
            cin>>board[i][j];
    refl(n , board);
    }

return 0;
}

它说&#34; n&#34;和&#34;董事会&#34;在函数中没有声明它们。

1 个答案:

答案 0 :(得分:1)

尝试使用C ++ std::vector或旧版C malloc + free

C ++

#include <string>
#include <iostream>
#include <vector>

using namespace std;

void reflxx(int n, vector<vector<int>>& board)
{
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {

            cout << board[i][j]  << "  ";
            }
        cout << endl; //printing the matrix to the screen
    }
}

int main()
{
    int n;
    string refl;
    cin>>n;
    vector<vector<int>> board(n, vector<int>(n));
     //creates a n*n matrix or a 2d array.

        for(int i=0; i<n; i++)    //This loops on the rows.
    {
        for(int j=0; j<n; j++) //This loops on the columns
            cin>>board[i][j];
    }
    reflxx(n , board);

return 0;
}

有关更多示例,请参阅http://www.cplusplus.com/reference/vector/vector/resize/