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

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

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 the 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:

⮚ 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

⮚ 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

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

 
Also See:

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