What is 3D Array (Three-Dimensional Array) in C?
A 3D array is an array with three indexes.
You can think of it as multiple 2D tables stacked together. A 3D array stores data in the form of layers × rows × columns.
data_type array_name[x][y][z];x→ number of layersy→ number of rowsz→ number of columns
2. Visual Thinking (Very Important)
Imagine:
- One 2D array = one sheet
- Many sheets stacked = 3D array
Like:
- Building floors (layers)
- Rooms on each floor (rows × columns)
3. Simple Example
int a[2][3][4];Meaning:
- 2 layers
- 3 rows per layer
- 4 columns per row
Total elements:
2 × 3 × 4 = 244. How Indexing Works
a[layer][row][column]Examples:
a[0][0][0] // first layer, first row, first column
a[1][2][3] // second layer, third row, fourth columnIndexes always start from 0.
5. Initializing a 3D Array
int a[2][2][3] = {
{ // Layer 0
{1, 2, 3},
{4, 5, 6}
},
{ // Layer 1
{7, 8, 9},
{10, 11, 12}
}
};6. Visual Table Representation
Layer 0
1 2 3
4 5 6Layer 1
7 8 9
10 11 127. Accessing Elements
printf("%d", a[1][0][2]);Explanation:
- Layer 1
- Row 0
- Column 2
Output:
9