C
This post will discuss how to initialize a 2D array with all 0’s in C.
1. Using Initialization Syntax
To initialize a 2D array with zeros, you can make use of the explicit initialization property of the arrays, which states that the uninitialized part of an array is initialized with static storage duration. Consider the array declaration – int array [M][N] = {1};
, which sets the element at the first column in the first row to 1 and all other elements to 0.
We can use this trick to explicitly initialize only the first element of the array with 0, causing the remaining elements to be initialized with zeros automatically. This is demonstrated below for a 4 × 4
matrix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> // M x N matrix #define M 4 #define N 4 int main(void) { int mat[M][N] = { 0 }; // print the 2D array for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { printf("%d ", mat[i][j]); } printf("\n"); } return 0; } |
Output:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
2. Using memset()
function
You can also use the memset()
function to initialize array elements with 0 or -1, which overwrites the allocated memory with 0’s or 1’s.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> #include <string.h> // 2D array dimentions #define M 4 #define N 4 int main(void) { int mat[M][N]; memset(mat, 0, sizeof(mat)); // print the matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { printf("%d ", mat[i][j]); } printf("\n"); } return 0; } |
Output:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
3. Using Designated Initializers
Finally, you can use designated initializers and name the array indices to be initialized within the initializer list. Its usage is demonstrated below, where the code explicitly initializes the first element of the array, and the remaining elements are automatically initialized with 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <stdio.h> // 2D array dimentions #define M 4 #define N 4 int main(void) { int mat[M][N] = { [0][0]=0 }; // print the matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { printf("%d ", mat[i][j]); } printf("\n"); } return 0; } |
Output:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
That’s all about initializing a 2D array with zeros in C.
Rate this post
Average rating 5/5. Vote count: 12
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
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 :)
Software Engineer | Content Writer | 12+ years experience