Array
Array are just many boxes put together in a line.
Arrays
Variables are nice, but what if we need to store a hundred integers 🤔 ?
Although this method is possible, it is not efficient or feasible. Hence, we use Array.
An array is another type of variable. It is a container for multiple values of the same type. Arrays carry type information and can only carry one type of value in one array. Think of arrays as cabinets, and each value belongs in one drawer in a cabinet.
An array must have a constant length, specified either at declaration or interpreted at initialization.
Refer to cppreference for more details.
Array Declaration
The following is the syntax for declaration: <element_type> <array_name>[<size (optional)>];
The []
(square brackets) specifies an array.
The following is an example of declaring a float array with length 10;
Array Initialization
An array can be initialized alongside a declaration with values, by using the initializer expression, like so:
If you initialize using the initializer expression, you are not required to specify the array length. It will count the number of elements and set the length as that.
Uninitialized arrays in functions store garbage values as initial values. If you want to initialize them as all 0
s do the following:
Arrays cannot be re-assigned, so you cannot use the initializer expression after the declaration statement, nor assign them to another array variable.
❗ Index: The first index of an array ❗ Boundary Issue: Accessing an array out of bounds is undefined behavior, it may not generate any error when used. (Read more.)
Array Access
Array items do not have a name we can call, but they are arranged in an orderly fashion within an array. We can access items using an index. We count from 0 in programming, so we can call, e.g. the 0th item in array x. The index can be a variable containing an integer, or simply an integer literal. The following is the syntax of array access: <array_name>[<index>]
For example:
Accessing outside the array region is an undefined behavior but may not generate any error when used. Values are retrieved at other memory addresses that do not belong to the array and the values are not guaranteed as the same across machines. Accessing outside of program memory will produce a "SIGSEGV Signal Segmentation Fault" runtime error.
Arrays are usually used for loops, to iterate over the length of the array for data manipulation.
This example populates the array with natural numbers:
Multidimensional Arrays
Arrays can have multiple dimensions. The arrays we have explored above are called 1D arrays.
To declare arrays with additional dimensions, just do as follows:
The above declares a 5-by-10 array.
To access a cell, it can be done as:
Alternatively, you can consider multidimensional arrays as matrices. For example:
map[4][3]
can be written in the matrix as below:
Last updated