An array is a collection of elements, all of the same type, stored in contiguous memory locations. It allows you to store multiple values of the same data type under a single variable name. Arrays are used when you need to store a fixed number of values of the same type and access them using an index.
Key Characteristics of Arrays in C:
- Fixed Size: The size of the array must be defined at compile time, and it cannot be changed during program execution.
- Zero-based Indexing: Array indices start from 0. For an array of size
n
, the valid indices are0
ton-1
. - Homogeneous: All elements in an array must be of the same data type, such as all integers or all floats.
Syntax for Declaring an Array:
data_type
: The type of data (e.g.,int
,float
,char
).array_name
: The name of the array.array_size
: The number of elements the array will hold.
Example:
Here, numbers
is an array that can store 5 integers. You can access these integers using indices from 0 to 4.
Initializing an Array:
You can initialize an array at the time of declaration.
Example 1: Explicit Initialization
Example 2: Implicit Initialization (Size Determined Automatically)
Example 3: Partially Initializing an Array
Accessing Array Elements:
You can access or modify elements in the array by using the index of the element. The index starts at 0
.
Example:
Multi-dimensional Arrays:
C also allows multi-dimensional arrays, where you can create arrays of arrays. The most common example is a 2D array (array of arrays), often used to represent matrices or grids.
Example of 2D Array:
Here, matrix
is a 2D array with 3 rows and 3 columns. To access an element, you need to specify both row and column indices:
Important Notes:
- Array Bounds: Accessing an array with an index outside of its defined range results in undefined behavior, which can lead to errors or unexpected results.
- Array Size: In C, the size of an array is fixed once defined, and this cannot be changed dynamically (unless using dynamic memory allocation, e.g.,
malloc()
).