Arrays
An array of intrinsic type consists of a rectangular (1-dimensional or multi-dimensional) set of elements which all have the same intrinsic type. Arrays allow individual elements or ranges of elements to be selected through indexing. Along with the type, an array is described by the bounds that are declared in its dimension
attribute. The latter determines the array's shape, a vector stating the extent of the array in each dimension. The rank of the array is the number of elements in its shape vector; the product of all the extents in the shape vector is the size of the array.
Arrays can be defined in three ways:
Static |
|
Dynamic |
|
Automatic |
|
Static arrays
The shape of a static array is specified through parameters or literal constants in the declaration section of a program unit (program
, function
, or subroutine
, e.g.). The memory for a static array is allocated on the stack. Note that the size of the stack is limited. Examples:
Dynamic arrays
The rank (number of dimensions) is defined in the declaration section of a program unit. Colons (:
) are used as placeholders. The allocatable
attribute must also be specified. The size of the array is set when memory is allocated in the executable part of a program unit. After an allocate
is called, its success can be checked by returning the status (0 indicates success); returning the status is optional. A non-zero status indicates a failure.
Arrays may be deallocated with the deallocate
statement. Allocatable arrays come into existence with the allocate
statement and vanish either when they are deallocated or at the end of the program. Dynamic arrays are often favored over static arrays because they are allocated on the heap, which is essentially unlimited; and they can be deallocated when no longer needed, freeing up unused memory. Examples: