Arrays

An array is a collection of variables of the same type. Individual array elements are identified by an integer index. In C the index begins at zero and is always written inside square brackets.

We have already met single dimensioned arrays which are declared like this


int results[20];

Arrays can have more dimensions, in which case they might be declared as


int results_2d[20][5];
int results_3d[20][5][3];

Each index has its own set of square brackets.

Where an array is declared in the main function it will usually have details of dimensions included. It is possible to use another type called a pointer in place of an array. This means that dimensions are not fixed immediately, but space can be allocated as required. This is an advanced technique which is only required in certain specialised programs.

When passed as an argument to a function, the receiving function need not know the size of the array. So for example if we have a function which sorts a list (represented by an array) then the function will be able to sort lists of different sizes. The drawback is that the function is unable to determine what size the list is, so this information will have to be passed as an additional argument.

As an example, here is a simple function to add up all of the integers in a single dimensioned array.


int add_array(int array[], int size)
{       int i;
        int total = 0;

        for(i = 0; i < size; i++)
                total += array[i];

        return(total);
}

  Go to Constants     Go to Index               Go to Expressions