将矩阵传递给函数

Passing matrix to a function

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

在调用'printMat'函数时出现错误。我的要求是在接受行数和列数后创建一个矩阵,然后将输入输入到矩阵中,然后通过发送矩阵调用printMat并打印元素。错误如下:

错误:参数'a'包含指向未知数组的指针Und 'int []'

#include<iostream>
using namespace std;
int row,col;
void printMat(int* a[])
{
    for(int i=0; i<row; ++i)
    {
        for(int j=0; j<col; ++j)
        {
            cout<<a[i][j]<<" ";
        }
    }
}
int main()
{   
    cin>>row;
    cin>>col;
    int mat[row][col];
    for(int i=0; i<row; ++i)
    {
        for(int j=0; j<col; ++j)
        {
            cin>>mat[i][j];
        }
    }
    printMat(mat);
    return 0;
}
int* a[]

是一个指针数组,但是你传递的是指向数组的指针:

int (*a)[]

它不起作用的原因是数组只是一个噩梦。在c++中,我们使用vector s。

#include<iostream>
#include<vector>
using namespace std;

void printMat(vector<vector<int>> mat)
{
    for(vector<int> one_row : mat)
    {
        for(int one_cell_in_this_row : one_row)
        {
            cout << one_cell_in_this_row << ' ';
        }   
        cout << endl;
    }   
}   
int main()
{   
    int row,col;
    cin>>row;
    cin>>col;
    vector< vector<int> >   mat( row , vector<int>(col,0) );
    //                            ^                 ^
    // initialize the vector ~~~~~/                 |
    // with 'row' items, each                       |
    // of which is a vector                         |
    // of 'col' integers.  ~~~~~~~~~~~~~~~~~~~~~~~~~/
    for(int i=0; i<row; ++i)                 
    {                                        
        for(int j=0; j<col; ++j)             
        {                                    
            int current_entry;
            cin>>current_entry;
            mat.at(i).at(j) = current_entry;
        }
    }
    printMat(mat);
    return 0;
}

您可以使用指针算法解决。参见以下代码:

#include<iostream>
using namespace std;
int row,col;
void printMat(int *a)
{
    for(int i=0; i<row; ++i)
    {
        for(int j=0; j<col; ++j)
        {
            cout<< *((a+i*col) + j)<<" ";
        }
    }
}
int main()
{
    cin>>row;
    cin>>col;
    int mat[row][col];
    for(int i=0; i<row; ++i)
    {
        for(int j=0; j<col; ++j)
        {
            cin>>mat[i][j];
        }
    }
    printMat((int *)mat);
    return 0;
}

其他可能的解决方案在这个链接中有解释