next up previous contents
Next: Masked Assignment Up: Arrays Previous: Array Constructors   Contents

Allocatable Arrays

In F90 temporary arrays can be dynamically created, used, and then discarded at will; the necessary memory is grabbed, used, and then put back (dynamic heap storage).

The declaration

real, dimension(:), allocatable :: A
states that A is a temporary matrix; no memory is allocated at the time of declaration; the size of A is irrelevant at this point, and the precise specification of the shape is deferred until the allocation point. In F90 jargon, A is said to be a deferred-shape array; in contrast, the ``standard'' declaration
real, dimension(5,5) :: B
makes B an explicit-shape array.

To reserve memory for A, we use

allocate( A(-1:3,2:5), STAT=ierr )
Upon completion of the function, the integer variable ierr reports the success of the allocation process: if everything is ok, and if the allocation request was denied.

The intrinsic inquiry function

allocated( A )
returns a logical result: .TRUE. if A is allocated, and .FALSE. otherwise.

Heap storage is reclaimed using

if( allocated(A) ) deallocate( A, stat=ierr )
(this deletes the array from memory and returns the space as free space in the heap). ierr reports the succes of the dealloction function. Note that we check first if A was allocated.

There is always an overhead in managing dynamic arrays; therefore, if the size of the array is known, the memory restrictions are not tight, or the arrays are needed during most of the program's lifetime, one should preffer explicit-shape arrays.

Attention: a deffered-shape array allocated in a procedure should be deallocated upon return - otherwise the memory space becomes inaccesible for the rest of the program's life (an inaccessible memory chunk is called ``garbage'').

An allocatable array in a procedure can be SAVEd. For example,

subroutine ...
real, allocatable, dimension(:,:), save :: A
...
if (.not.allocated(a)) allocate(A(10,10)
A is allocated during the first call to the subroutine; after the procedure termination, A will remain allocated and its value preserved becaude of the SAVE attribute; following calls to the subroutine will ``see'' that A was already allocated and will work with the old values.




next up previous contents
Next: Masked Assignment Up: Arrays Previous: Array Constructors   Contents
Adrian Sandu 2001-08-26