Lesson 9.2. Array initialization


In C, an array can be initialized in its entirety at the time of its declaration and only at the time of its declaration. The syntax consists in putting between two braces the values of the cells separated by commas:

int tab[5] = { 12, 25, 65, 11, 7};

This initialization creates an array with the following values:

$$ tab = \begin{bmatrix} 12 \\ 25 \\ 65 \\ 11 \\ 7 \end{bmatrix} $$

If the number of values between the braces is less than the size of the table, only the first cells (concerned) will be initialized.

When initializing at the declaration, if the size of the table is not specified between the square brackets, the size of the table will automatically adapt. For example, the following line creates an array of 3 cells:

int tab[] = {1,2,3};

If you have to initialize an array outside its declaration, you have to


Exercise 1

Write a program that creates declares and initializes an array with the first 5 odd numbers. The program then displays the contents of the array according to this example:

tab[0] = 1
tab[1] = 3
tab[2] = 5
tab[3] = 7
tab[4] = 9

Exercise 2

Modify the code of the previous exercise so that the table now contains the 1000 first odd numbers :

tab[0] = 1
tab[1] = 3
tab[2] = 5
tab[997] = 1995
tab[998] = 1997
tab[999] = 1999


Which syntaxes can be used for initializing an array?

Check Bravo! When the array size is not specified, it adapts to the size of the initialization. Try again...

How to initialize an array outside its declaration?

Check Bravo! It is only at the declaration that you can initialize an entire array. Try again...

Let's consider the following initialization. What is in tab[2]?

int tab[3] = { 10, 20 };
Check Bravo! The third cell is not initialized. Try again...

What is the size of this array?

char tab[] = { 10, 20, 30, 40 };
Check Bravo! 4 cells x 1 bytes = 4 bytes = 32 bits Try again...

See also

Last update : 11/23/2022