Passing a 2D array to a C++ function using reference

Passing 2-D array isnt as tough as you are making it out to be! I want to ask you, is it necessary for you to pass using pointers? If not, then simply use-

#include<bits/stdc++.h>
using namespace std;
 
int r, c=0;
void print(int a[][4])
{
for(size_t i=0; i<r; i++)
{
for(size_t j=0; j<c; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
 
int main()
{

cin>>r>>c;
int arr[r][4];
 
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
cin>>arr[i][j];
}
}
print(arr); //
return 0;
}

The few keypoints you need to know are-

  1. For a 2-D array, number of columns MUST be known while passing.
  2. Specifying rows is optional, and is usually avoided.
  3. In your function, row and column aren’t declared in scope of that function. You need to pass the information of the row and column to the function as well.
  4. Number of column must be a constant, not a variable. If its stored in a variable, it should be like

Also, refer these links-

3 Likes