Recently I encountered a problem in a company’s coding round which had a question of rotating a matrix in multiples of 90 degrees. The catch for me was not the algorithm or rotation of array but to “pass the 2-D array in a function”. The question is definitely a good one, but here I will scrutinize the passing of a matrix as an argument in C++.

I tried to figure it out during the contest but was unable to do it back then, obviously because of the limited time allotted for the completion of the challenge. So I immediately converted my code to C language.

Here’s a straightforward way to do it in C language:

void func(int m, int n, int arr[][n])       //function prototype
{ 
    printf("%d", arr[0][0]);    //accessing an element of the array
}

The main function would look like this:

int main() 
{   int m, n;
    scanf("%d %d", &m,&n);
    int arr[m][n]; 
    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            scanf("%d", &arr[i][j]);
    func(m, n, arr);                          //function call

    return 0; 
}

As simple as it seems!

But a similar solution would throw errors in C++.

After the contest was over, I was very curious to find the problem in my code as I have been using C++ for a long time in coding competitions but didn’t clash with a problem of such kind earlier. I tried StackOverflow solutions and even asked my old training teacher to help me out with it. He told the same C solution we already discussed above. Then I contacted one of my favorite YouTubers, for the same. He told me to use vectors.

So, I will discuss below all viable solutions I found out:

It is pretty easy if the number of rows and columns are constants or defined using macros.

#2d-arrays #coding #pointers #c #cplusplus #programming-c

Passing a 2-D Array as a Function Parameter in C++(mainly)/C
1.15 GEEK