Array Initialization
Declaring an array only reserves memory — it does not automatically give the elements sensible values. C offers several ways to initialize an array's contents at the point of declaration, each with slightly different behavior that is worth knowing precisely.
Initializer List Syntax
The most common way to initialize an array is with a brace-enclosed, comma-separated list of values:
int arr[5] = {1, 2, 3, 4, 5};
double temps[3] = {36.6, 37.0, 38.2};
char vowels[5] = {'a', 'e', 'i', 'o', 'u'};0, the second to index 1, and so on.Partial Initialization
#include <stdio.h>
int main(void) {
int arr[5] = {1, 2}; // only 2 values given
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
// arr[0] = 1
// arr[1] = 2
// arr[2] = 0 (zero-filled)
// arr[3] = 0 (zero-filled)
// arr[4] = 0 (zero-filled)
return 0;
}int arr[100] = {0}; is a common idiom to zero-initialize an entire array in one line — the first element is explicitly set to 0, and every remaining element is zero-filled by the same rule.Size Inference from the Initializer
If you omit the size and provide an initializer list, the compiler counts the values and sizes the array to match automatically:
int arr[] = {1, 2, 3}; // compiler infers size 3
char name[] = "Hello"; // compiler infers size 6 (5 letters + '\0')
// sizeof(arr) / sizeof(arr[0]) == 3, computed at compile timeDesignated Initializers (C99+)
#include <stdio.h>
int main(void) {
int arr[10] = {[3] = 5, [7] = 42};
for (int i = 0; i < 10; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
// every element is 0 except arr[3] == 5 and arr[7] == 42
return 0;
}Uninitialized Elements Contain Garbage
int arr[5]; as a local variable — its elements start out containing whatever garbage bytes happened to already be in that memory. This is exactly the same rule that applies to ordinary uninitialized scalar local variables. Reading an uninitialized element before assigning it a value produces unpredictable results and is a very common source of bugs.int arr[5]; // NOT initialized -- contains garbage values
int zeroed[5] = {0}; // IS initialized -- every element is guaranteed 0int arr[5] = {1,2,3,4,5};initializes elements in order using a brace listFewer values than the declared size zero-fills the remaining elements
int arr[] = {1,2,3};lets the compiler infer the array size from the initializerDesignated initializers (C99+), e.g.
int arr[10] = {[3] = 5};, set specific indices and zero-fill the restAn array with NO initializer at all contains garbage, just like an uninitialized scalar