Arrays

An array is a data structure consisting of a collection of elements (values or variables) of the same data type. Each storage location in an array is called an array element and is identified by an array index or key. The lowest index address corresponds to the first element and the highest index address to the last element.

Declare an array

The declaration statement for an array is similar to a variable declaration with the exception that the number of array elements is specified inside square brackets after the array name –

int example[5];

The example array (above) declares 5 sequential integers. This declaration causes the compiler to set aside enough memory to hold all 5 int elements. The array element number is also is called the array subscript.

Initialising Arrays

Arrays can be initialised when they are first declared by use of the equal sign followed by a list of values enclosed in braces and separated by commas:

int example[5]= { 10, 20, 30, 40, 50 };

In the example above, the value 10 is assigned to example[0], the value 20 is assigned to example[1], the value 30 is assigned to the example[2], the value 40 is assigned to example[3]  and the value 50 is assigned to example[4].  If the array size is omitted, the compiler creates an array large enough to hold the initialisation values. The following statement would have the same effect as the previous array declaration statement:

int example[] = { 10, 20, 30, 40, 50 };

Although the number of initialisation values can be fewer than the number of array elements, too many initialisers ie more initialisers than array elements will cause the compiler to generate an error. Any array element not initialised will contain an unknown value

Multidimensional Array

A multidimensional array has more than one subscript. A two-dimensional array has two subscripts and a three-dimensional array has three subscripts.  There is no limit to the number of C array dimensions although the size of an array will be limited by the amount of memory on the computer. The following declaration for a two-dimensional array will be able to hold 64 int values

int example[8][8];

Multidimensional arrays can also be initialised by assigning array elements in order. For
example:

int array[2][4] = { 1, 2, 3, 4, 5, 6, 7, 8 };

which can also be written

array[2][4]={{1,2,3,4},{5,6,7,8}};

results in the following assignments:

array[0][0]=1
array[0][1]=2
array[0][2]=3
array[0][3]=4
array[1][0]=5
array[1][1]=6
array[1][2]=7
array[1][3]=8

Accessing Data Stored in an Array

An element is accessed by indexing the array name. This is done by placing the element index within square brackets after the array name. These indexes are called zero-based because the first element in an array is at index 0. The first integer value stored in an array arraydata[10] is arraydata[0] , the second is arraydata[1] , and so on. The index of the last element in an array is always (Length of Array – 1) or arraydata[9].