Skip to main content

Microcontrollers

Section 14.3 Arrays

When variables are related to each other, it may be prudent to store the data in an array. An array, which must be initialized with the number of values to be given in the array, can store any type of variable (char, int, long, float). Each element in the array is defined by its index. Index numbers always go from 0 to (\(n-1\)), where \(n\) is the number of values in the array. The syntax for defining an array is shown below.
datatype arrayName[sizeofArray];
To access the \((m+1)^{th}\) element of an array (where \((m+1)\) is less than or equal to \(n\text{,}\) the number of elements in the array), use the syntax someVariable = arrayName[m]. To overwrite the \((m+1)^{th}\) element of an array (where \((m+1)\) is less than or equal to \(n\text{,}\) the number of elements in the array), use the syntax arrayName[m] = newValue.
While arrays can be populated with any type of variable, character arrays using ASCII formatting (not to be confused with char arrays!) require a special precaution in that they must contain a null character (\0) at the end. Therefore, if they are assigned with the number of elements, that number must be \(n+1\text{.}\) Optionally, the number in square brackets can be left out.

Example 14.3.1. Declaring, accessing, and overwriting array elements.

An array named myArray containing six unsigned char elements is declared below.
unsigned char myArray[6] = {0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6};
The code used to save the 6th element of the array to a new unsigned char variable named a is shown below. (Because arrays are zero-indexed, the number one must be subtracted from the element to obtain the index number.)
unsigned char a = myArray[5];
The code used to overwrite the second element of the array to the number 13 is shown below.
myArray[1] = 13;

Subsection 14.3.1 Multi-Dimensional Arrays

Data can be stored into a multi-dimensional array. An array consisting of values of the datatype int, for example, int a[n][m] has n rows and m columns of data. This means that \(n \times m\) elements can be stored into the array. Memory considerations must be taken into account before defining large arrays, which is especially true in multi-dimensional arrays, as memory can expand non-linearly with the addition of new elements.

Example 14.3.2. Multi-Dimensional Array.

An example two-dimensional array consiting of values that are unsigned char is declared below.
unsigned char wholeNums[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}};