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

In this post, we will see how to pass 2D array to a function as a parameter in C.


 

In the previous post, we have discussed how to dynamically allocate memory for 2D array. In this post, we will see how we can pass 2D array to a function in C programming language.

 

1. For Static Array

If we know the array bounds at compile time, we can pass a static 2D array to a function in C as shown below.

 

Download   Run Code

Output:

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

 
If we don’t know the array bounds at compile time, we need to pass the array bounds to the function as shown below. This will only work if array is passed after the indices to the function.

 

Download   Run Code

Output:

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

 

2. Using Array of Pointers

When the array bounds are not known until runtime, we can dynamically create an array of pointers and dynamically allocate memory for each row. Then we can pass the array of pointers to a function as shown below.

 

Download   Run Code

Output:

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

 

3. Using 1D array

We can even use a 1D array to allocate memory for a 2D array. This can be done both statically and dynamically as shown below:

 

3.1. Static Array

 

Download   Run Code

Output:

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

 

3.2. Dynamic Array

 

Download   Run Code

Output:

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

 

4. Using Double Pointer

If the function parameter is a pointer to a pointer, we can do something like:

 

Download   Run Code

Output:

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

 

 
Also See: How to Pass 2D Array as a Function 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