Initializing Arrays
3. Filling Up Your Array’s Lockers
So, you’ve declared an array, but it’s just an empty container at this point. You need to fill it with some values! There are a few ways to initialize an array in C. The simplest is to provide a list of initial values when you declare the array:
`int numbers[5] = {1, 2, 3, 4, 5};`
Here, we’re creating an integer array called `numbers` with a size of 5, and we’re initializing it with the values 1, 2, 3, 4, and 5. The values are assigned to the array elements in the order they appear in the list. What if you provide fewer values than the array size? The remaining elements will be initialized to 0 (for numeric types) or NULL (for pointers). For example:
`int incomplete[5] = {1, 2, 3}; // incomplete[3] and incomplete[4] are now equal to 0`
You can also initialize an array element by element using a loop, often a `for` loop. This is particularly useful when you want to calculate the values or read them from an external source.
For example:
`int squares[5];for (int i = 0; i < 5; i++) { squares[i] = i * i;}`
Here, the array `squares` will store the squares of the numbers from 0 to 4 (0, 1, 4, 9, 16). It’s important to make sure that you do not go out of the array boundary or memory corruption could ensue. That is, don’t make the value of i greater or equal than 5 in the example above.