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
Selected Reading
Initialization of a multidimensional arrays in C/C++
Multidimensional arrays in C are arrays of arrays, where each element is itself an array. They are used to represent data in multiple dimensions like matrices, tables, or grids. The most common type is a 2D array, but C supports arrays of any dimension.
Syntax
// Declaration and initialization
data_type array_name[size1][size2]...[sizeN] = {
{{values}, {values}},
{{values}, {values}}
};
// Or with partial initialization
data_type array_name[size1][size2] = {{val1, val2}, {val3, val4}};
Example 1: 2D Array Initialization
Here's how to initialize and work with a 2D array in C −
#include <stdio.h>
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("Size of the array: %zu bytes\n", sizeof(arr));
printf("Content of the 2D array:\n");
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
Size of the array: 24 bytes Content of the 2D array: 1 2 3 4 5 6
Example 2: 3D Array Initialization
This example demonstrates initializing a 3D array with explicit values −
#include <stdio.h>
int main() {
int arr[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
printf("3D Array content:\n");
for(int i = 0; i < 2; i++) {
printf("Layer %d:\n", i);
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
printf("arr[%d][%d][%d] = %d ", i, j, k, arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
3D Array content: Layer 0: arr[0][0][0] = 1 arr[0][0][1] = 2 arr[0][1][0] = 3 arr[0][1][1] = 4 Layer 1: arr[1][0][0] = 5 arr[1][0][1] = 6 arr[1][1][0] = 7 arr[1][1][1] = 8
Example 3: Partial Initialization
You can initialize only some elements, and the rest will be set to zero −
#include <stdio.h>
int main() {
int arr[3][3] = {{1, 2}, {3}}; /* Partial initialization */
printf("Partially initialized array:\n");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
Partially initialized array: 1 2 0 3 0 0 0 0 0
Key Points
- In array declaration like
int arr[2][3], the first dimension can be omitted during initialization:int arr[][3] = {...} - All dimensions except the first must be specified in function parameters
- Memory is allocated contiguously in row-major order
- Uninitialized elements are automatically set to zero
Conclusion
Multidimensional arrays in C provide an efficient way to store and manipulate structured data. Proper initialization ensures predictable behavior and optimal memory usage in your programs.
Advertisements
