Derived Types and Allocatable
Allocatable Array
Runtime Size
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
nums ← allocated size=3
4integer :: i5allocate(nums(3))6do i = 1, 3values this stepallocated size=3numsnums(1) ← 10
6do i = 1, 37 nums(i) = i * 108end dovalues this step10nums(1)1inums(2) ← 20
6do i = 1, 37 nums(i) = i * 108end dovalues this step20nums(2)2inums(3) ← 30
6do i = 1, 37 nums(i) = i * 108end dovalues this step30nums(3)3iprint '(I0)', sum(nums)
8end do9print '(I0)', sum(nums)10deallocate(nums)output60values this step[10, 20, 30]numsnums ← deallocated
9 print '(I0)', sum(nums)10 deallocate(nums)11end program allocatable_array_demovalues this stepdeallocatednums
Follow the Allocation
allocate(nums(3))reserves three integer slots.- The loop fills
nums(1),nums(2), andnums(3). - The values become
10,20, and30. sum(nums)adds them to get60.- The program prints
60, thendeallocate(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.