Department of Engineering

IT Services

9. Arrays

department image More realistic programs need to store and process a substantial number of items of data. The types of variable considered so far have been simple data types capable of holding a single value.

Arrays are a consecutive group of variables (memory locations) that all have the same type and share a common name. In many applications, arrays are used to represent vectors and matrices.

Declaration

An array is declared by writing the type, followed by the array name and size (number of elements in the array) surrounded by square brackets.

   type             array-name[ number-elements ];
   float           position[3];
   int             count[100];
   char            YourSurname[50];            

The above examples declare position to be an array which has 3 elements which are real numbers (e.g. 3D vector). YourSurname contains 50 characters (e.g. storing a surname) and count is an array of 100 integer values.

An array can have any legal variable name but it cannot have the same name as an existing variable. The array's size is fixed when the array is declared and remains the same throughout the execution of the program.

Array elements and indexing

To refer to a particular element of the array we specify the name of the array and the position number or index of the particular element. Array elements are counted from 0 and not 1. The first elements will always have position and index 0 and the last element will have index number (position) N-1 if the array has N elements.

The first elements in the arrays declared above are referred to by position[0], count[0] and YourSurname[0] respectively. The last element of an array declared as array[N] with N elements is referred to by array[N-1]. The last elements of the example arrays above are therefore referred to by position[2], count[99] and YourSurname[49] respectively.

Here's another example: if you want to store some integer information about each month in an array, you could use

   
int month[12];

to reserve space for 12 integers. Inside the computer the memory layout will be something like this

array

The integers have the names month[0], month[1] ... month[11] because array indexing starts at 0. Array items are usually referred to as elements. They're stored contiguously in memory.

The index of an array can also be an expression yielding an integer value.

Assigning values to array elements

Elements of an array can be treated like other variables but are identified by writing the name of the array followed by its index in square brackets. So for instance the statements:

   marks[1] = 90.0;
   scaled[1] = (marks[1] - mean)/deviation;

show how the second element of an array called marks is assigned a value and how the second element of the array scaled is assigned the result of a calculation using this element value.

What is useful about arrays is that they fit well with the use of loops. For example:

   int count[100];
   for(i=0; i< 100; i++)
   {
      count[i] = 0;
   }

can be used to initialise the 100 elements of an integer array called count by setting them all to 0. The following program uses arrays and repetition loops to calculate the scalar product of two vectors input by the user.

// ScalarProduct.cc
// Calculating the scalar product between vectors input by user

#include <iostream>
using namespace std;

int main()
{
   float vectorA[3], vectorB[3], scalar=0.0;
   int i;
           
   // Get input vectors from user.
   cout << "Enter elements of first vector: " << endl;
   for(i=0;i<3;i++)
   {
      cin >> vectorA[i];
   }
   cout << "Enter elements of second vector: " << endl;
   for(i=0;i<3;i++)
   {
      cin >> vectorB[i];
   }
  
   // Calculate scalar product.
   for(i=0;i<3;i++)
   {
      scalar = scalar + (vectorA[i] * vectorB[i]);
   }

   // Output result.
   cout << "The scalar product is " << scalar << endl;
   return 0;
}

Note: care must be taken never to try and assign array elements which are not defined. Its consequences on the execution of the program are unpredictable and hence very difficult to detect and debug. It is left to the programmer to check that the array is big enough to hold all the values and that undefined elements are not read or assigned.

(When an array of N elements is declared the compiler is told that it expects N elements and sets aside memory for each element. For an array with N elements the array element addressed by array[N] is not defined. Unfortunately when N is a variable the compiler cannot check this and it cannot therefore prevent the programmer trying to assign this value. In fact it is allowing the programmer to write to or read the memory location of array[N] which may contain another variable. The consequences are usually disastrous and the value of a variable in the program will have its value changed without the programmer being aware that this has occurred.)

Passing arrays to functions

Function definition and prototype

To pass an array argument to a function, the array type and name is included in the formal parameter list (i.e. in the function definition and prototype parameter list). You should also include the square brackets with the size of the array. The latter is optional with one-dimensional arrays, although it might be convenient to pass the number of items in the array as one of the parameters. The following is a function header for a function which receives an array of real numbers.

Function call

In C++, the entire array may be passed using the array name (and no square brackets). This looks similar to pass by value but is actually very different. The actual parameter passed to the function, the name of the array, is in fact the memory address of the first element of the array. The important point to note here is that (as with passing by reference) when you pass an array to a function you will be able to access and modify the values of any of its elements.

In the following call to the NormaliseData() function, a 300 element array, marks, is passed to the function:

   NormaliseData(marks, 300);

The function can read and change the value of any of the elements of the array.

Of course if you only need to pass a single element of the array and you want to take advantage of the simplicity and safety of passing by value, this can be done, for example, by having marks[2] as an actual parameter in the call to the function. For example in the following function:

   float ProcessIndividual(float mark);       //Function prototype
   scaledMark = ProcessIndividual(marks[2]);  //Function call

the call passes the value of marks[2] which it stores as a local variable (mark). Changes to the value of the local variable will not affect the value in the calling function.

Back to top