C++ Course Listing

 

Arrays

by Matthew Martin

Arrays are a means to gather large amounts of data of the same type together.

Contents

Declaring An Array

Initialisation

Accessing Aray Elements

Multidimensional Arrays

Take Care With Arrays

top of page


Declaring An Array


Arrays are decalred using the following syntax:
type array-name[size];
e.g. to declare an integer array of a size able to hold 50 integer values:
int myarray[50];

Initialisation


An array may be initialised by using curly braces containing the values to be placed in each element of the array separated by commas, e.g.:
int count[6] = {1,2,3,4,5,6};

top of page


Accessing Array Elements


Each component unit of an array is called an element. Each element may be accessed for reading and writing by referencing its number. However, the number of the first element is always zero. This means that the number of the last element is one less than the number used to declare the array. Using the above example of the integer array myarray, to access the first element in the array to put a value there:
myarray[0] = 12;
To access the last element in the array and put a value there:
myarray[49] = 7;
Forgetting that the element referencing starts at zero (not one) is a common source of programming errors (bugs).

top of page


Multidimensional Arrays


Arrays may have more than one dimension. Two declare a two-dimensional array:
int prices[5][2];
The above example declares an integer array called price of two dimensions, the first dimension has 5 elements and the second dimension has 2 elements.
To access an element the reference of both dimensions must be used, e.g.:
prices[2][2] = 5;
The above example places the value 5 in the element referenced as 2, 2.
It is possible to have many dimensions to an array (n-dimensions). For example a twelve dimensional array of floating point values may be declared like this:
float temperatures[31][28][31][30][31][30][31][30][30][31][30][30];
The elements in a multidimensional array are actually continuous in memory. This means that it is possible to iterate through the elements.

top of page


Take Care With Arrays


When iterating (or decrementing) through the elements in an array care is required because there is nothing to stop areas outside the defined areas of the array being overwritten. A common programming error takes the form:


int count[5];

for (i=1; i<6; i++){
count[i] = i;
}


The problem with the above code is that the variable i is iterated to 6 within the for loop. This means that a memory area outside the bounds of the array is accessed. This will almost certainly cause errors while the program is running. The same issue also applies reading from array elements. It is important when writing code to pay attention to the accuracy of the code and to perform testing on the code.

 

by Matthew Martin

top of page