Derived Types and Allocatable
Allocatable in Derived Type
A derived type can hold an allocatable component, giving a bag-of-values with runtime size.
Program
Play the program to allocate and fill an inner array, then sum it.
allocatable_in_type.f90
Replay: real traced execution (multi-file project)
program allocatable_in_type_demo
implicit none
type :: bag
integer, allocatable :: items(:)
end type bag
type(bag) :: b
allocate(b%items(3))
b%items = [5, 7, 9]
print '(I0)', sum(b%items)
end program allocatable_in_type_demo
b%items ← allocated size=3
6type(bag) :: b7allocate(b%items(3))8b%items = [5, 7, 9]values this stepallocated size=3b%itemsb%items ← [5, 7, 9]
7allocate(b%items(3))8b%items = [5, 7, 9]9print '(I0)', sum(b%items)values this step[5, 7, 9]b%itemsprint '(I0)', sum(b%items)
8 b%items = [5, 7, 9]9 print '(I0)', sum(b%items)10end program allocatable_in_type_demooutput21values this step[5, 7, 9]b%items
Follow the Bag
type baghas an allocatableitemsarray.allocate(b%items(3))reserves three slots insideb.b%items = [5, 7, 9]fills those slots.sum(b%items)adds5 + 7 + 9.- The program prints
21. | component slot | value | | --- | --- | |b%items(1)| 5 | |b%items(2)| 7 | |b%items(3)| 9 | | sum | 21 |
allocatable component
`integer, allocatable :: items(:)` makes the component sized at run time.
allocate component
`allocate(b%items(3))` allocates inside the instance.
array assign
`b%items = [5, 7, 9]` fills the allocated array in one statement.
Exercise: allocatable_in_type.f90
Reproduce the printed value 21, then change one item value and predict the new sum before running it.