Pointers & Dynamic Data Structures

Fortran pointers carry shape information (they're descriptors), and may only point to target or pointer objects.

17.1 Pointers and targets

Fortran pointers carry shape information (they're descriptors), and may only point to target or pointer objects. Prefer allocatables for ownership; use pointers for aliasing and linked structures.

real, target :: a(10)
real, pointer :: p(:) => null()    ! always initialize pointers
real, pointer :: s => null()

a = [(real(i), i = 1, 10)]
p => a(2:10:2)                     ! pointer to a section (alias, no copy)
p = 0.0                            ! modifies a(2), a(4), ...
print *, associated(p), associated(p, a(2:10:2))
nullify(p)

allocate(s)                        ! pointer to dynamically allocated memory
s = 3.14
deallocate(s)                      ! must deallocate manually (else leak)

real, pointer :: m(:, :)
m(1:2, 1:5) => a                   ! bounds remapping (rank change, F2003)

17.2 Linked list

module linked_list
  implicit none
  type :: node
    integer :: value
    type(node), pointer :: next => null()
  end type node
contains
  subroutine push_front(head, v)
    type(node), pointer, intent(inout) :: head
    integer, intent(in) :: v
    type(node), pointer :: new
    allocate(new)
    new%value = v
    new%next => head
    head => new
  end subroutine push_front

  subroutine print_list(head)
    type(node), pointer, intent(in) :: head
    type(node), pointer :: cur
    cur => head
    do while (associated(cur))
      write(*, '(i0, 1x)', advance='no') cur%value
      cur => cur%next
    end do
    print *
  end subroutine print_list

  subroutine free_list(head)
    type(node), pointer, intent(inout) :: head
    type(node), pointer :: tmp
    do while (associated(head))
      tmp => head%next
      deallocate(head)
      head => tmp
    end do
  end subroutine free_list
end module linked_list

17.3 Allocatable components for recursive structures (F2008)

type :: tree
  integer :: value
  type(tree), allocatable :: left, right     ! recursive allocatable components: auto-freed
end type tree

17.4 Pointer pitfalls

Dangling pointers (pointing to deallocated memory), memory leaks, aliasing that prevents optimization. Use contiguous attribute for pointer arrays that are contiguous to help performance.