In C++, a 3D array is a multidimensional array that has three dimensions, i.e. it can grow in three directions. In this article, we will learn how to pass a 3D array to a function in C++.
Pass a 3D Array to a Function in C++
Just like normal 1-dimensional arrays, we can’t pass the array to a function directly, we must pass the 3D array to a function as a pointer. The array will suffer the array decay and lose the information about its dimensions so we need to pass the dimensions separately.
Syntax
function_type name (type (*arr)[col][dpt], int row, int col, int dpt)
where *arr is a pointer to a 3D array with dimensions row, col, and dpt.
C++ Program to Pass a 3D Array to a Function
// C++ program to pass a 3D array to a function #include <iostream> using namespace std;
// function to print the elements of a 3D array void printArray( int arr[][3][3], int row, int col, int dpt)
{ for ( int i = 0; i < row; ++i) {
for ( int j = 0; j < col; ++j) {
for ( int k = 0; k < dpt; ++k) {
cout << arr[i][j][k] << " " ;
}
cout << endl;
}
cout << endl;
}
} int main()
{ // intialize the 3D array
int arr[3][3][3] = {
{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } },
{ { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } },
{ { 19, 20, 21 }, { 22, 23, 24 }, { 25, 26, 27 } }
};
// pass the 3D array to the function
printArray(arr, 3, 3, 3);
return 0;
} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
Time Complexity: O(1) as the time complexity of passing is not dependent on array size.
Auxiliary Space: O(1) as the array is passed by pointer.