可分配的陣列
陣列可以具有可分配的屬性:
! 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。