Ways to pass a 2D array to a function are as follows:-
- When both dimensions are available globally.
Code:
C++ Code
#include <bits/stdc++.h>
const int n = 3, m = 3;
void display(int nums[n][m]){
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++)
std::cout << nums[i][j] << ' ';
std::cout << std::endl;
}
}
int main(){
int nums[n][m] = {{1 ,2 ,3}, {4, 5, 6}, {7, 8, 9}};
display(nums);
}
Output:
1 2 3
4 5 6
7 8 9
- When only column size is available globally.
Code:
C++ Code
#include <bits/stdc++.h>
const int m = 3;
void display(int arr[][m], int n){
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++)
std::cout << arr[i][j] << " ";
std::cout << std::endl;
}
}
int main(){
int arr[][m] = {{1 ,2 ,3}, {4, 5, 6}, {7, 8, 9}};
display(arr, 3);
}
Output:
1 2 3
4 5 6
7 8 9
- If your compiler is C99 compatible then passing of variable-sized arrays are allowed. We do it by passing the variable-sized dimensions.
Code:
C Code
#include <stdio.h>
void display(int r, int c, int arr[][c]){
for(int i = 0; i<r; i++){
for(int j = 0; j<c; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main(){
int arr[][2] = {{1, 2}, {3, 4}};
int r = 2, c = 2;
display(r, c, arr);
}
Output:
1 2
3 4
- We can use a single pointer to pass an array as an argument.
Code:
C++ Code
#include <bits/stdc++.h>
using namespace std;
void print(int *nums, int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
cout<<*((nums+i*c) + j)<<" ";
}
cout<<endl;
}
}
int main()
{
int nums[][3] = {{2, 4, 6}, {8, 10, 12}, {14, 16, 18}};
int r = 3, c = 3;
print((int *)nums, r, c);
return 0;
}
Output:
2 4 6
8 10 12
14 16 18
- We know that we can use a pointer that can point towards an array. With this concept, we can pass an array as an argument.
Code:
C++ Code
#include <bits/stdc++.h>
const int m=3;
void display(int (*arr)[m]){
for(int i = 0; i<m; i++){
for(int j = 0; j<m; j++)
std::cout << arr[i][j] << " ";
std::cout << std::endl;
}
}
int main(){
int nums[][3] = {{2, 4, 6}, {8, 10, 12}, {14, 16, 18}};
display(nums);
}
Output:
2 4 6
8 10 12
14 16 18
- Using Double pointers(pointer to pointer)
Code:
C++ Code
#include <bits/stdc++.h>
void display(int **arr, int r, int c){
for(int i = 0; i<r; i++){
for(int j = 0; j<c; j++)
std::cout << arr[i][j] << ' ';
std::cout << std::endl;
}
}
int main(){
int r, c;
std::cin >> r >> c;
int** arr = new int*[r];
for(int i = 0; i<r; i++)
arr[i] = new int[c];
for(int i = 0; i<r; i++)
for(int j = 0; j<c; j++)
std::cin >> arr[i][j];
display(arr, r, c);
}
Special thanks to Asish Kumar for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article