# Pass an 2D array to a function in C++

posted Sep 15

We cannot pass an entire array as an argument in the function because C++ does not allow it. However, there are other ways to pass an array to a function. We can easily pass a single dimension array to a function using a pointer but passing a 2d array to a function can be difficult.

# Methods

• Using a pointer

In this method, we have to typecast the 2D array when passing.

``````#include <stdio.h>
void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"
print((int *)arr, m, n);
return 0;
} ``````

Output

`1 2 3 4 5 6 7 8 9`
• Specifying the size of the column
``````#include<iostream>
using namespace std;

void processArr(int a[][2]) {
cout << "element at index 1,1 is " << a[1][1];
}
int main() {
int arr[2][2];
arr[0][0] = 0;
arr[0][1] = 1;
arr[1][0] = 2;
arr[1][1] = 3;

processArr(arr);
return 0;
}``````

Output

`element at index 1,1 is 3`
• Pointer to a pointer
``````void processArr(int **a) {
// Do Something
}
// When calling:
int **array;
array = new int *[10];
for(int i = 0; i <10; i++)
array[i] = new int[10];
processArr(array);``````

Hope this will help.

100 points
7 2