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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

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.