Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
4 Dimensional Array in C/C++
A 4 dimensional array in C is an array of 3 dimensional arrays, where each 3D array contains multiple 2D arrays, and each 2D array contains multiple 1D arrays. This creates a hierarchical structure with four levels of indexing.
Syntax
datatype array_name[dimension1][dimension2][dimension3][dimension4];
For example:
int arr[3][2][3][4]; /* 3 blocks, 2 tables, 3 rows, 4 columns */
Declaration and Initialization
You can initialize a 4D array during declaration using nested braces −
#include <stdio.h>
int main() {
int arr[2][2][2][3] = {
{
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {0, 1, 2} }
},
{
{ {10, 11, 12}, {13, 14, 15} },
{ {16, 17, 18}, {19, 20, 21} }
}
};
printf("Element at arr[0][1][0][2]: %d\n", arr[0][1][0][2]);
printf("Element at arr[1][0][1][1]: %d\n", arr[1][0][1][1]);
return 0;
}
Element at arr[0][1][0][2]: 9 Element at arr[1][0][1][1]: 14
Traversing a 4D Array
To access all elements, you need four nested loops −
#include <stdio.h>
int main() {
int arr[2][2][2][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} }
}
};
for (int i = 0; i < 2; i++) {
printf("Block %d:\n", i);
for (int j = 0; j < 2; j++) {
printf(" Table %d:\n", j);
for (int k = 0; k < 2; k++) {
printf(" Row %d: ", k);
for (int l = 0; l < 3; l++) {
printf("%d ", arr[i][j][k][l]);
}
printf("\n");
}
}
}
return 0;
}
Block 0:
Table 0:
Row 0: 1 2 3
Row 1: 4 5 6
Table 1:
Row 0: 7 8 9
Row 1: 10 11 12
Block 1:
Table 0:
Row 0: 13 14 15
Row 1: 16 17 18
Table 1:
Row 0: 19 20 21
Row 1: 22 23 24
Memory Size Calculation
The memory size of a 4D array is calculated as: dimension1 × dimension2 × dimension3 × dimension4 × sizeof(datatype)
#include <stdio.h>
int main() {
int arr[3][2][3][4];
int total_elements = 3 * 2 * 3 * 4;
int memory_size = sizeof(arr);
printf("Total elements: %d\n", total_elements);
printf("Memory size: %d bytes\n", memory_size);
printf("Size per element: %lu bytes\n", sizeof(int));
return 0;
}
Total elements: 72 Memory size: 288 bytes Size per element: 4 bytes
Key Points
- 4D arrays require four indices:
arr[block][table][row][column] - Memory is allocated contiguously in row-major order
- Use four nested loops to traverse all elements
- Total memory = product of all dimensions × sizeof(datatype)
Conclusion
4D arrays in C provide a way to organize data in four dimensions, useful for complex data structures like time-series matrices or multi-dimensional grids. They follow the same principles as lower-dimensional arrays but require careful indexing and initialization.
