How to Pass 2D Array as a Function Parameter in C++

In this post, we will see how to pass 2D array as a function parameter in 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. Using 1D Array

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

 

2.1. Static 1D Array

 

Download   Run Code

 

 

2.2. Dynamic 1D Array

 

Download   Run Code

 

3. Using Array of Pointers

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

 

Download   Run Code

 

Also See: How to Pass 2D Array to a Function as a Parameter in C

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz