Fortran 可分配数组

示例

数组可以具有可分配的属性:

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

这将声明变量,但不会为其分配任何空间。

! 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

一旦不再需要一个变量,就可以释放它:

deallocate(foo)

如果由于某种原因allocate语句失败,程序将停止。如果通过stat关键字检查状态,可以防止这种情况:

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

该deallocate语句也具有stat关键字:

deallocate (geese, stat=status)

status 是一个整数变量,如果分配或取消分配成功,则值为0。