简体   繁体   中英

How to Pass 2D array to a function in C++

I have a 2D array in C++ which takes input from the user. I want to pass this to a function. sample Code I written is:

 #include<bits/stdc++.h>
using namespace std;

void fun(int arr[n][m])
{
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cout<<arr[i][j]<<" ";
        }
        cout<<"\n";
    }
}

int main(int argc, char const *argv[])
{
    int n,m;
    cin>>n>>m;
    int arr[n][m];
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cin>>arr[i][j];
        }
    }
    fun(arr);
    return 0;
}

What is the correction I should do in code so I can access the 2d array in function?

Your function needs to take three arguments.

The array pointer, m, and n

void fun(int *arr, int n, int m) {
    // whatever
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM