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.

Download  Run Code

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.

Download  Run Code

3. Using standard for-loop

Finally, we can initialize a multidimensional array with any value using nested for-loops.

Download  Run Code

 
C also allows multidimensional arrays to be iterated through by a base-element pointer. So, we can do something like:

 
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:

Initialize a matrix in C++