Arrays
- Arrays
- Arrays are variables that can store many items of the same type. The individual items known as elements, are stored sequentially and are uniquely identified by the array index (sometimes called a subscript).
Arrays:
- May contain any number of elements.
- Elements must be of the same type.
- The index is zero based.
- Array size (number of elements) must be specified at declaration.
How to Create an Array
Syntax
type arrayName [size];
- size refers to the number of elements.
- size must be a constant integer.
Example
How to Initialize an Array at Declaration
Syntax
type arrayName [size] = {item1, …, itemn};
The items must all match the type of the array.
Example
How to Use an Array
Arrays are accessed like variables, but with an index.
Syntax
arrayName [index]
- index may be a variable or a constant.
- The first element in the array has an index of 0.
- C does not provide any bounds checking.
Example
Creating Multidimensional Arrays
Add additional dimensions to an array declaration.
Syntax
type arrayName [size1]…[sizen];
- Arrays may have any number of dimensions.
- Three dimensions tend to be the largest used in common practice.
Example
Initializing Multidimensional Arrays at Declaration
Syntax
type arrayName [size0]…[sizen] =
{{item,…,item},
.
.
.
{item,…,item}};
Example
Visualizing 2-Dimensional Arrays
Visualizing 3-Dimensional Arrays
Array Processing
- Arrays are frequently processed as part of a loop since the same operation needs to be performed on each element.
- Operations might include:
- Sending strings of characters to or reading strings of characters from a UART.
- Performing a mathematical transform on an array of floating-point numbers (think digital filters).
- The loop count variable will often be used as the array index itself or in conjunction with the array index.