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
real, allocatable :: readings(:)declares shape but no size.allocate (readings(n))claims the storage whennis known.- Assigning
[readings, 3.0]reallocates to the new shape;deallocatereleases it.
Keywords and builtins used here
allocatableallocatedeallocateendimplicitintegernoneprintprogramreal
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.
Step 2 of 3 in Types & memory, step 20 of 27 in Language basics.