An allocatable array gets its size at run time with allocate, and is released with deallocate.

Program

Play the program to allocate three slots, fill them, and total them.

allocatable_array.f90
Replay: real traced execution (multi-file project)
program allocatable_array_demo
    implicit none
    integer, allocatable :: nums(:)
    integer :: i
    allocate(nums(3))
    do i = 1, 3
        nums(i) = i * 10
    end do
    print '(I0)', sum(nums)
    deallocate(nums)
end program allocatable_array_demo
  1. nums ← allocated size=3

    4integer :: i5allocate(nums(3))6do i = 1, 3
    values this stepallocated size=3nums
  2. nums(1) ← 10

    6do i = 1, 37    nums(i) = i * 108end do
    values this step10nums(1)1i
  3. nums(2) ← 20

    6do i = 1, 37    nums(i) = i * 108end do
    values this step20nums(2)2i
  4. nums(3) ← 30

    6do i = 1, 37    nums(i) = i * 108end do
    values this step30nums(3)3i
  5. print '(I0)', sum(nums)

    8end do9print '(I0)', sum(nums)10deallocate(nums)
    output60
    values this step[10, 20, 30]nums
  6. nums ← deallocated

    9    print '(I0)', sum(nums)10    deallocate(nums)11end program allocatable_array_demo
    values this stepdeallocatednums

Follow the Allocation

  1. allocate(nums(3)) reserves three integer slots.
  2. The loop fills nums(1), nums(2), and nums(3).
  3. The values become 10, 20, and 30.
  4. sum(nums) adds them to get 60.
  5. The program prints 60, then deallocate(nums) releases the storage. | slot | value | | --- | --- | | nums(1) | 10 | | nums(2) | 20 | | nums(3) | 30 | | sum | 60 |
allocatable `integer, allocatable :: nums(:)` declares without a size.
allocate `allocate(nums(3))` reserves storage at run time.
deallocate `deallocate` releases the storage.

Exercise: allocatable_array.f90

Reproduce the printed value 60, then change one assigned slot value and predict the new sum before running it.