Initialize multidimensional arrays in C
This post will discuss how to initialize multidimensional arrays in the C programming language.
A multidimensional array is an array with more than one dimension. The simplest multidimensional array is the 2D array or two-dimensional array. It is basically an array of arrays, which is also commonly known as a matrix. The general array initialization syntax applies to multidimensional arrays as well.
1. Using Static Storage
All objects in C with static storage duration are set to 0, which were not explicitly initialized by the programmer. The following code initializes the first cell of a 6 × 8 matrix to 0, and the rest of the elements as if they had static storage duration, i.e., initialized with zero.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <stdio.h> int main(void) { int mat[6][8] = { 0 }; // or, use {{ 0 }} int r = sizeof(mat)/sizeof(mat[0]); int c = sizeof(mat[0])/sizeof(mat[0][0]); // print the matrix for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { printf("%d ", mat[i][j]); } printf("\n"); } return 0; } |
2. Using memset() function
We can also use the memset() function to initialize a multidimensional array with 0 or -1. The memset() function overwrites the allocated memory of the array with 0’s or 1’s. This works with both fixed-length and variable-length multidimensional arrays.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> #include <string.h> int main(void) { const size_t R = 6; const size_t C = 8; int mat[R][C]; memset(mat, 0, sizeof(mat[0][0]) * R * C); // print the matrix return 0; } |
3. Using standard for-loop
Finally, we can initialize a multidimensional array with any value using nested for-loops.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> int main(void) { const size_t R = 6; const size_t C = 8; int mat[R][C]; int value = 1; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { mat[i][j] = value; } } // print the matrix return 0; } |
C also allows multidimensional arrays to be iterated through by a base-element pointer. So, we can do something like:
|
1 2 3 |
for (int i = 0; i < R*C; i++) { *((int*)mat + i) = 0; } |
Note that the global and static arrays are initialized with their default values when no initializer is specified. For instance, a global integer array will be zero-initialized by default.
That’s all about initializing multidimensional arrays in C.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)