Allocatable arrays
| Allocate | |
| Query shape | |
| Move_alloc | |
| Automatic reallocation |
Allocate
An allocatable array starts without storage, and the allocate statement reserves the requested size only when the program knows it.
Always pair allocation with deallocation when the array is no longer needed, which keeps long running programs lean.
The program below reserves ten elements, fills them, and then releases the storage.
program demo
implicit none
real, allocatable :: v(:)
allocate(v(10))
v = 0.0
print *, size(v)
deallocate(v)
end program demo
Query shape
Intrinsics report everything about an array without changing it: size counts the elements, while lbound and ubound report the index range.
The allocated intrinsic tells whether storage currently exists, which guards code that may receive an empty array.
This fragment prints the size and bounds of a small vector.
program demo
implicit none
real, allocatable :: v(:)
allocate(v(4))
if (allocated(v)) print *, size(v)
print *, lbound(v), ubound(v)
deallocate(v)
end program demo
Move_alloc
The move_alloc routine transfers storage from one allocatable to another without copying the elements.
After the move the source is deallocated and the destination owns the memory, which makes growing buffers cheap.
Here the data built in tmp becomes the final array v in one efficient step.
program demo
implicit none
real, allocatable :: v(:), tmp(:)
allocate(tmp(3))
tmp = [1.0, 2.0, 3.0]
call move_alloc(tmp, v)
print *, v
end program demo
Automatic reallocation
Assignment to an unallocated allocatable reserves exactly the needed size, and assignment with a new shape resizes it on the spot.
This rule removes most manual allocate calls for results of expressions and array constructors.
The example assigns two vectors of different lengths in a row, and the array follows along each time.
program demo
implicit none
real, allocatable :: v(:)
v = [1.0, 2.0]
print *, size(v)
v = [1.0, 2.0, 3.0, 4.0]
print *, size(v)
end program demo
Next: Pointers in Fortran
Article author: Arthur Isaev