Pointers in Co-array Fortran
module pointers_example
implicit none
contains
! We'll show how pointers work in contrast to values with
! 2 subroutines: `zeroval` and `zeroptr`. `zeroval` has an
! integer parameter, so arguments will be passed to it by
! value. `zeroval` will get a copy of `ival` distinct
! from the one in the calling program.
subroutine zeroval(ival)
integer, intent(inout) :: ival
ival = 0
end subroutine zeroval
! `zeroptr` in contrast has an integer pointer parameter.
! The `iptr` in the subroutine body can be used to change
! the value at the referenced address.
subroutine zeroptr(iptr)
integer, pointer, intent(inout) :: iptr
iptr = 0
end subroutine zeroptr
subroutine main()
integer :: i
integer, pointer :: p
i = 1
print *, "initial:", i
call zeroval(i)
print *, "zeroval:", i
! The `p => i` syntax associates the pointer `p` with the target `i`.
p => i
call zeroptr(p)
print *, "zeroptr:", i
! In Fortran, we can print the address of a variable using the loc() function
print *, "pointer:", loc(i)
end subroutine main
end module pointers_example
program run_example
use pointers_example
call main()
end program run_example
To compile and run this Co-array Fortran program:
$ gfortran -coarray=single pointers_example.f90 -o pointers_example
$ ./pointers_example
initial: 1
zeroval: 1
zeroptr: 0
pointer: 140732920744208
zeroval
doesn’t change the i
in main
, but zeroptr
does because it has a reference to the memory address for that variable.
In Co-array Fortran, pointers work differently from some other languages. They are more like references and must be associated with a target before use. The =>
operator is used for pointer assignment.
The loc()
function is used to get the memory address of a variable, which is similar to the &
operator in some other languages.
Note that Co-array Fortran is an extension of Fortran and may require specific compiler support. The -coarray=single
flag is used here for simplicity, but in a true co-array program, you might use multiple images for parallel execution.