typestar

Allocatable arrays in Fortran

An array whose size waits for run time, grows on assignment, and cleans up.

program allocatable_arrays
    implicit none
    real, allocatable :: readings(:)
    integer :: n = 5

    ! allocatable defers the size to run time.
    allocate (readings(n))
    readings = [2.1, 3.4, 4.8, 3.9, 2.6]
    print *, "holding ", size(readings), " readings"

    ! Assignment can reallocate: the array takes the new shape.
    readings = [readings, 3.0]
    print *, "grew to  ", size(readings)
    deallocate (readings)
    print *, "released"
end program allocatable_arrays

How it works

  1. real, allocatable :: readings(:) declares shape but no size.
  2. allocate (readings(n)) claims the storage when n is known.
  3. Assigning [readings, 3.0] reallocates to the new shape; deallocate releases it.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
441
Tokens
77
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 2 of 3 in Types & memory, step 20 of 27 in Language basics.

← Previous Next →