Course Content
C Tutorial
About Lesson

Declaring and Initializing Arrays

In C programming, arrays provide a way to store multiple values of the same data type under a single name. Declaring an array involves specifying the data type of its elements and the size of the array.

Syntax for Declaring Arrays

The syntax for declaring an array in C is:

data_type array_name[array_size];

For example, to declare an array of integers named numbers with a size of 5:

int numbers[5];

Initializing Arrays

Arrays in C can be initialized at the time of declaration or later in the program. Initialization involves assigning initial values to the elements of the array.

Initializing at Declaration

You can initialize an array during declaration by providing a list of values enclosed in curly braces {}.

int numbers[5] = {1, 2, 3, 4, 5};

This initializes the numbers array with values 1, 2, 3, 4, and 5 at respective indices.

Partial Initialization

It’s also possible to partially initialize an array during declaration. For example:

int numbers[5] = {1, 2}; // Initializes the first two elements as 1 and 2, and sets the rest to 0

Initializing Arrays without Specifying Size

Starting from the C99 standard, C allows initializing arrays without explicitly specifying the size if the size can be inferred from the number of elements provided.

int numbers[] = {1, 2, 3, 4, 5}; // Compiler infers the size as 5

Accessing Array Elements

Array elements are accessed using indices starting from 0. For example, to access the third element of the numbers array:

int third_element = numbers[2]; // Arrays are zero-indexed, so the third element is at index 2