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
  1. b%items ← allocated size=3

    6type(bag) :: b7allocate(b%items(3))8b%items = [5, 7, 9]
    values this stepallocated size=3b%items
  2. b%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%items
  3. print '(I0)', sum(b%items)

    8    b%items = [5, 7, 9]9    print '(I0)', sum(b%items)10end program allocatable_in_type_demo
    output21
    values this step[5, 7, 9]b%items

Follow the Bag

  1. type bag has an allocatable items array.
  2. allocate(b%items(3)) reserves three slots inside b.
  3. b%items = [5, 7, 9] fills those slots.
  4. sum(b%items) adds 5 + 7 + 9.
  5. 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.