Fortran Allocatable arrays


Example

Arrays can have the allocatable attribute:

! One dimensional allocatable array
integer, dimension(:), allocatable :: foo
! Two dimensional allocatable array
real, dimension(:,:), allocatable :: bar

This declares the variable but does not allocate any space for it.

! We can specify the bounds as usual
allocate(foo(3:5))

! It is an error to allocate an array twice
! so check it has not been allocated first
if (.not. allocated(foo)) then
  allocate(bar(10, 2))
end if

Once a variable is no longer needed, it can be deallocated:

deallocate(foo)

If for some reason an allocate statement fails, the program will stop. This can be prevented if the status is checked via the stat keyword:

real, dimension(:), allocatable :: geese
integer :: status

allocate(geese(17), stat=status)
if (stat /= 0) then
  print*, "Something went wrong trying to allocate 'geese'"
  stop 1
end if

The deallocate statement has stat keyword too:

deallocate (geese, stat=status)

status is an integer variable whose value is 0 if the allocation or deallocation was successful.