An array in C is initialized by assigning values to its elements at the time
of declaration using an initializer list enclosed in curly braces {}
. Here
are the common ways to initialize an array in C:
-
Initialize with all elements specified:
You can declare and initialize an array by listing all its elements inside braces. For example:c int arr[] = {1, 2, 3, 4, 5};
This creates an array of size 5 with values 1, 2, 3, 4, and 5 in order
-
Partial initialization:
You can initialize only some elements, and the rest will be set to zero automatically if the array has static storage duration or if partially initialized. For example:c int arr[5] = {1, 2, 3};
Here, arr = 1
, arr[1] = 2
, arr[2] = 3
, and the remaining elements are
initialized to 0
-
Omitting the size:
When you provide an initializer list without specifying the size, the compiler infers the size from the number of elements in the list:c int arr[] = {10, 20, 30};
This creates an array of size 3
-
Initialize all elements to zero:
You can initialize all elements to zero by using{0}
:c int arr[5] = {0};
This sets all 5 elements to zero
-
Using loops for initialization:
Arrays can also be initialized element-by-element in a loop after declaration:c int arr[5]; for (int i = 0; i < 5; i++) { arr[i] = i * 2; }
This sets elements to 0, 2, 4, 6, 8 respectively
Summary of Syntax
c
// Declare and initialize with explicit size
int arr[5] = {1, 2, 3, 4, 5};
// Declare and initialize without size (size inferred)
int arr[] = {1, 2, 3};
// Partial initialization, rest zero
int arr[5] = {1, 2, 3};
// Initialize all to zero
int arr[5] = {0};
In all cases, the initializer list is a comma-separated list of constant
expressions inside braces {}
and is preceded by an equal sign =
. This is the standard and most common way to initialize arrays in C.