简体   繁体   中英

pass 2d array to a function in c++ with both values taken input in main method

#include <bits/stdc++.h>
using namespace std;
int M;
int N;
int K;
int temp=0;
void leftrotate(int A[M][N])
{

    for(int i=0;i<M;i++)
    {
        temp=A[i][0];
        int j;
        for(j=0;j<N-1;j++)
        {
            A[i][j]=A[i][j+1];
        }
        A[i][j]=temp;
    }

    for(int i=0;i<M;i++)
    {
        for(int j=0;j<N;j++)
        {
            cout<<A[i][j];
        }
    }
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>M;
        cin>>N;
        cin>>K;
        int A[M][N];
        for(int i=0;i<M;i++)
        {
            for(int j=0;j<N;j++)
            {

                cin>>A[i][j];
            }
        }
        leftrotate(A);
    }
    return 0;
}

As you can see inside main function the values of m and n are taken dynamically and all the variables are defined globally. Now I need to call the function leftrotate with the 2d array as parameter. What is the way to do that with or without pointers ?

For multidimensional dynamic array you can use:

vector<vector<int>> A

or

int **A

Sample:

void leftrotate(int **A)
{

    for(int i=0;i<M;i++)
    {
        temp=A[i][0];
        int j;
        for(j=0;j<N-1;j++)
        {
            A[i][j]=A[i][j+1];
        }
        A[i][j]=temp;
    }

    for(int i=0;i<M;i++)
    {
        for(int j=0;j<N;j++)
        {
            cout<<A[i][j];
        }
    }
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>M;
        cin>>N;
        cin>>K;
        int **A = new int*[M];
            for(int i = 0; i < M; i++)
                A[i] = new int[N];

        for(int i=0;i<M;i++)
        {
            for(int j=0;j<N;j++)
            {

                int p;
                cin>>p;
                A[i][j] = p;
            }
        }
        leftrotate(A);

        for(int i = 0; i < M; ++i) {
            delete [] A[i];
        }
        delete [] A;
    }
    return 0;
}

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