A subtle point in Fortran 90 pointer

by Yi Zhang

Though I found out it today, what’s discussed below is already pointed out at here.

First, a few toy lines of f90 ‘s pointer feature.

program main

integer, ALLOCATABLE, TARGET :: a(:), c(:)
integer, POINTER :: b1(:)

allocate(a(3))
allocate(c(3))
allocate(b1(3))

a = [3,4,893]
c = [4,5,90]
b1 = a
write(*,*) b1                 ! b1 pointed to a
a = c
write(*,*) b1                 ! b1 pointed to a or c ?
deallocate(a)
write(*,*) b1                 ! b1 deallocated along with a ?
deallocate(c)
deallocate(b1)                ! b1 deallocated with a
write(*,*) b1

end program main

The output is:

% a.out
           3           4         893
           3           4         893
           3           4         893

Explanation:

The first and last output are trivial: just the content of b1 and null (blank line).  What’s interesting is the 2nd and 3rd output. At the 2nd output, “a” is reassigned with “c”, but the pointer “b1” still gives “a” ‘s initial value, the same happens at 3rd output, when “a” is already deallocated. This is what pointed out by the link mentioned above: assignment operator gives an temporary copy, which persists even after the original version is destroyed (DEALLOCATED). This gives a subtle way of assigning pointers: by updating the same array and using assignment operator, different values of the array could be assigned to different pointers.

Advertisements