In many languages a pointer points to an address. This is very flexible, but also very error-prone. In Fortran a pointer has attributes such as rank and type that must match whatever it is pointing to, and targets must be explicitly designated as such. This is a very different, much more restrictive definition of a pointer that avoids many of the common errors generated by the simple address pointers but can take some getting used to. I think that you will find that pointers are rarely needed in Fortran and are generally best avoided except in rare cases, as perhaps in several (common) specific cases â linked lists first come to mind.
Donât use them out of habit if you come at Fortran from something like a C programming background. In Fortran they should be treated more as a necessary evil than as a principal method.
Fortran (perhaps more than any other language(?)) has quite a few restrictions specifically to help prevent coding errors that sometimes feel limiting but are basically a compromise between not allowing a feature at all or allowing it, but in as safe a manner as possible. Fortran pointers certainly fall into that category.
To truly understand Fortran pointers you also need to understand that bounds are applied to them as well. You canât simply start striding through memory based off their values. If you understand this example you are well on your way to understanding Fortran pointers. They probably should have been given a different name, as the term âpointerâ carries a lot of baggage for anyone familiar with them as commonly implemented in other languages.
Forget everything you know about pointers from other languages when working with Fortran pointers and treat them as a new paradigm is my advice.
program show_ptr
implicit none
real, target :: x
real, dimension(:), pointer :: y
real, dimension(3), target :: z
real, pointer :: a, b, c
z=[10.0,20.0,30.0]
x = 1.0
a=>z(1)
b=>z(2)
c=>z(3)
!NO!y(1:1) => z(3)
y(20:20) => z(3:3)
write(*,*) y, size(y), shape(y),lbound(y),ubound(y)
y(30:30) => z(2:2)
write(*,*) y, size(y), shape(y),lbound(y),ubound(y)
!NO!y(3:1:-1)=>z
y=>z
y(1:3)=>z
write(*,*) y, size(y), shape(y),lbound(y),ubound(y)
write(*,*)a,b,c
end program show_ptr