This post will discuss how to pass a 2D array as a function parameter in the C++ programming language.

1. Static Array

If we know the array dimensions at compile-time, we can pass the array by reference using a function template in C++, as shown below:

Download  Run Code

 
The advantage of using this approach is that there is no need to specify the array dimensions. The disadvantage of using this approach is that we can’t use it with dynamic arrays.

We can also create a wrapper over the function, as shown below, which is more efficient for large arrays:

Download  Run Code

2. 1D Array

We can even use a 1D array to allocate memory for a 2D array by allocating one huge block of M×N memory. This can be done both statically and dynamically, as shown below:

⮚ Static 1D Array

Download  Run Code

⮚ Dynamic 1D Array

Download  Run Code

3. Array of Pointers

When the parameter is an array of pointers, we can do something like:

Download  Run Code

That’s all about passing a 2D array as a function parameter in C++.

 
Also See:

Pass 2D array to a function as a parameter in C