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

How to pass a 2D array to a c++ function using reference efficiently?
I have tried but it show error .
code :

Instead of passing the array declare the array globally,then you can use the array where ever you want.

1 Like

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-

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]<<" ";
int main()

int arr[r][4];
for(int i=0; i<r; i++)
for(int j=0; j<c; 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-


@vijju123, Is there any way to pass a 2D array if no parameter is known without declaring it globally?

Read the 2nd link I gave. The Q you have is one of the good follow up questions, so i made sure to answer it as well. The answer there states that its better to use vectors for this purpose. (Vector of vectors).

However, the standard library supplies std::vector container, that works very well for multi-dimension arrays: in your case, passing vector<vector<int> > &matrix would be the proper way of dealing with the task in C++.

thanks! :slight_smile:

I told you many times that there exist some other section of clearing your doubt. But still you repeat the same process again and again. At least try to search by google, you can get plenty of information in one go.

Please take some tips from @vijju123 for how to use google or other websites like geeksforgeeks, stakeoverflow, quora, mathstackexhange etc. He is expert in this.

Hey &bansal1232 , i have tried at least 3 hours in above code and searched in google. I post codechef forum, when i can not solve . Probably u did not show my code. I request u see my code and then comment me.