Pointers in Fortran
| Point with => | |
| Associated test | |
| Nullify | |
| Prefer allocatables |
Point with =>
A Fortran pointer is an alias: it refers to another variable instead of owning storage of its own.
Only a variable declared with the target attribute can be pointed at, and the link is made with the => operator.
The program below points p at val, so a change through p is visible in val.
program demo
implicit none
real, target :: val
real, pointer :: p
val = 10.0
p => val
p = p + 5.0
print *, val
end program demo
Associated test
The associated intrinsic reports whether a pointer currently points at something, which prevents accidental use of a dangling alias.
Check association before reading through a pointer that may still be empty, especially after optional setup steps.
This fragment prints one message when p is linked and another when it is not.
program demo
implicit none
real, target :: val
real, pointer :: p
nullify(p)
if (associated(p)) print *, "linked"
p => val
if (associated(p)) print *, "linked"
end program demo
Nullify
Nullify breaks the link between a pointer and its target without touching the target value itself.
A freshly declared pointer starts in an undefined state, so nullify it or point it at something before the first associated test.
The example links p, uses the target, and then safely disconnects the pointer.
program demo
implicit none
real, target :: val
real, pointer :: p
val = 3.0
p => val
print *, p
nullify(p)
print *, associated(p)
end program demo
Prefer allocatables
Allocatables are the safer default: they own their memory, clean up on their own, and cannot dangle the way pointers can.
Reach for a pointer only when aliasing is truly required, such as walking a linked structure or retargeting one name to several targets in turn.
The same storage below is managed with an allocatable and needs no nullify or association test at all.
program demo
implicit none
real, allocatable :: v(:)
allocate(v(3))
v = [1.0, 2.0, 3.0]
print *, v
deallocate(v)
end program demo
Next: DO CONCURRENT
Article author: Arthur Isaev