Initialize an Array in C With Examples

In this article, we’ll take a look at how we will initialize an array in C.

There are different ways through which we can do this, so we’ll list them all one by one. Let’s get started!


Method 1: Initialize an array using an Initializer List

An initializer list initializes elements of an array in the order of the list.

For example, consider the below snippet:

This initializes an array of size 5, with the elements {1, 2, 3, 4, 5} in order.

This means that arr[0] = 1, arr[1] = 2, and so on.

We don’t need to initialize all the elements 0 to 4. We can even do only from indices 0 to 2.

The following code is also valid:

But now, arr[4] and arr[5] will still remain garbage values, so you need to be careful!

If you’re using an initializer list with all elements, you don’t need to mention the size of the array.

If you want to initialize all the elements to 0, there is a shortcut for this (Only for 0). We can simply mention the index as 0.

Output

If you’re using multi-dimensional arrays, you can still initialize them all in one block, since arrays are stored in a row-wise manner.

Output

A similar method can also be used for other datatypes, like float, char, char*, etc.

Output

Remember, this method with [1 … 7] = “Journaldev” might not work with all compilers. I work on GCC in Linux.

Method 2: Initialize an array in C using a for loop

We can also use the for loop to set the elements of an array.

Output

Method 3: Using Designated Initializers (For gcc compiler only)

If you’re using gcc as your C compiler, you can use designated initializers, to set a specific range of the array to the same value.

Note that there is a space between the numbers and there are the three dots. Otherwise, the compiler may think that it is a decimal point and throw an error.

Output (for gcc only)

We can also combine this with our old initializer list elements!

For example, I am setting only array index arr[0], arr[8] as 0, while the others are designated initialized to 10!

Output


Conclusion

In this article, we learned how we could initialize a C array, using different methods.

For similar articles, do go through our tutorial section on C programming!


By admin

Leave a Reply