« previous next»

5.2    Allocatable Arrays
 

    Arrays can be very large and require a lot of memory; therefore, it is often useful to reserve this space only during the times that the array is required.  This cannot be done when the array size is declared during compilation.  For this reason it is useful to use the programs available run time memory called "free store" to allocate the memory for the array during program execution.  This memory can be used and restored using the following commands.

    An array is declared as ALLOCATABLE by:

    type, DIMENSION(:), ALLOCATABLE :: array names

for example:

    INTEGER, DIMENSION(:), ALLOCATABLE :: A

creates an integer array A that will have memory allocated to it (i.e. have it's size determined) during execution.

    Allocation occurs using the ALLOCATE command:

    ALLOCATE (array name(min:max))

Min  and max are the limits of the subscripts used.  If min is one then it need not be included in the declaration.  For example:

    ALLOCATE (A(20))

now the array A has space for 20 elements.  A STAT clause can be used to verify that  the allocation has been successful (much like READ or OPEN statements):

    ALLOCATE (A(20), STAT = allocate_status)
    IF (allocate_status /= 0) STOP "*** Not enough memory ***"

Program execution will stop if the allocation is not successful.  This is a good safeguarding tool.

    Once the array is no longer needed it is important to deallocate the memory so it can be used.  this involves the DEALLOCATE command.  Again, it is useful to use the STAT option to verify that the deallocation was successful.

    DEALLOCATE (A)
 

« previous next»