Skip to content
Allocatable Arrays and Pointers
step 1/5

Reading — step 1 of 5

Learn

~1 min readDerived Types and Allocation

Allocatable arrays — sized at runtime. Most flexible Fortran array form.

integer, allocatable :: a(:)

allocate(a(10))         ! size 10
a(1:10) = [(i, i=1, 10)] ! initialize
deallocate(a)            ! free

allocate(a(20))          ! reallocate with new size

Allocatable strings:

character(len=:), allocatable :: s
s = "hello"             ! length set automatically
s = s // " world"        ! grows
print *, len(s)          ! 11

Move semantics with move_alloc — transfer ownership without copy:

integer, allocatable :: a(:), b(:)
allocate(a(1000000))
call move_alloc(a, b)   ! b now owns the array, a is empty

Useful for large arrays — avoids the copy of b = a.

Pointers — explicit aliasing:

integer, target :: x = 5
integer, pointer :: p => null()

p => x                  ! p now points to x
print *, p              ! 5
p = 10                  ! sets x to 10

The pointed-to variable must have the target attribute. Pointers can't dangle — Fortran nullifies them on cleanup.

associated(p) checks if pointer is set:

if (associated(p)) then
    use_pointer(p)
end if

Allocatable vs pointer:

  • Allocatable — owns memory, automatic cleanup, faster, simpler
  • Pointer — alias to existing data, can be reassigned, more flexible but error-prone

Prefer allocatable. Use pointers only for genuine aliasing (linked lists, trees, sharing data with C).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…