How to Pass a 3D Array to a Function in C?
A 3D array (or three-dimensional array) in C is a multi-dimensional array that contains multiple layers of two-dimensional arrays stacked on top of each other. It stores elements that can be accessed using three indices: the depth index, row index, and column index. In this article, we will learn how to pass a 3D array to a function in C.
Passing 3D Array as Parameter to a Function in C
We cannot directly pass a 3D array to a function just like we do one-dimensional arrays. Instead, we must pass the 3D array to function as a pointer. When doing so, the array undergoes array decay, losing information about its dimensions. Therefore, we must pass the dimensions of the array separately.
Syntax
functionType funcName(type (*arr)[cols][depth], int rows, int cols, int depth)
Here,
- funcName: It is the name of the function.
- arr: It is the pointer which points to the 3D array.
- rows: It represents the number of 2D arrays.
- cols: It represents the number of rows in each 2D array.
- depth: It represents the number of columns in each 2D array.
C program to pass a 3D array to a function
The following program illustrates how we can pass a 3D array to a function in C.
// C program to pass a 3D array to a function
#include <stdio.h>
// Function to print the elements of a 3D array
void printArray(int arr[][3][3], int rows, int cols,
int depth)
{
printf("Elements of the 3D array:\n");
// Loop through each element in the 3D array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
for (int k = 0; k < depth; ++k) {
// Print each element
printf("%d ", arr[i][j][k]);
}
// Printing a new line at the end of each column
printf("\n");
}
// Printing a new line at the end of each row
printf("\n");
}
}
int main()
{
// Initialize the 3D array with fixed sizes
int arr[3][3][3] = {
{ { 10, 20, 30 }, { 40, 50, 60 }, { 70, 80, 90 } },
{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } },
{ { 190, 200, 210 },
{ 220, 230, 240 },
{ 250, 260, 270 } }
};
// Declare the dimensions of the array
int rows = 3;
int cols = 3;
int depth = 3;
// Pass the 3D array to the function
printArray(arr, rows, cols, depth);
return 0; // Return 0 to indicate successful execution
}
Output
Elements of the 3D array: 10 20 30 40 50 60 70 80 90 1 2 3 4 5 6 7 8 9 190 200 210 220 230 240 250 260 270
Time Complexity: O(1), as the time complexity of passing is not dependent on array size.
Auxiliary Space: O(1)