可分配的数组

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

! 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。