Part-2 3D Array


3 -Dimensional Array
Introduction
In C++, arrays are a foundational concept used to store multiple values of the same data type. While 1D and 2D arrays are quite common, understanding 3D arrays opens the door to managing more complex datasets such as multi-layered grids, volumetric data, and real-world matrix-based applications like 3D games or simulations.
In this article, we’ll explore:
What is a 3D array?
How to declare and initialize it
How elements are stored in memory
How to calculate addresses
Access methods using pointers
A relatable analogy to simplify understanding
What is a 3D Array?
A 3D array is essentially an array of 2D arrays. Think of it as a cube made up of several 2D matrix layers.
int a[2][3][4]; // 2 blocks (layers), each of 3 rows and 4 columns
Here:
2
represents number of blocks (depth or pages)3
represents number of rows4
represents number of columns
Total elements = 2 * 3 * 4 = 24
integers.
Initialization
You can initialize a 3D array manually or using nested loops.
int a[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
How is it Stored Internally?
Although declared as 3D, memory layout is still linear in RAM. Elements are stored in row-major order.
Example:
a[1][2][3] = *( *(*(a + 1) + 2) + 3);
Address Calculation:
If base address = B, then
Address of a[i][j][k] = B + ((i * R * C) + (j * C) + k) * size_of_datatype
Where:
i
= layerj
= rowk
= columnR
= total rowsC
= total columns
Example:
int a[2][3][4];
// For a[1][2][3], i=1, j=2, k=3, R=3, C=4
// Address = B + ((1*3*4) + (2*4) + 3) * sizeof(int)
Real-Life Analogy: Society Building Example
Imagine a society where:
There are multiple buildings
Each building has multiple floors
Each floor has multiple rows of flats
This is how a 3D array works:
Building = Layer =
i
Floor = Row =
j
Flat = Column =
k
To find a specific flat:
Go to building
i
Within that, go to floor
j
Then access the flat at position
k
This makes understanding nested levels much easier!
Accessing Elements
Using nested loops:
for (int i = 0; i < depth; i++) {
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++) {
cout << a[i][j][k] << " ";
}
cout << endl;
}
cout << "-----\n";
}
Memory Calculation
To determine memory used:
Total Bytes = depth * row * col * sizeof(data type)
Example:
int a[2][3][4];
// 2 * 3 * 4 * 4 bytes = 96 bytes
Conclusion
3D arrays are extremely powerful for storing and accessing volumetric data. Understanding their memory layout and addressing gives you an edge in building more optimized and scalable applications. Keep practicing with real-world analogies and coding exercises to master them!
Subscribe to my newsletter
Read articles from Amit Kesarwani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
