fortranallocatable-array

Why an allocated array gets unallocated when it is passed to a subroutine?


Passing an allocatable array via actual argument to a subroutine whose corresponding dummy argument is defined as an allocatable array:

module m
  real, allocatable :: a(:,:)
end module m

module m2
contains
  subroutine p(c)
    implicit none
    real, allocatable, intent(out):: c(:,:)
    write(*,*) 'allocated?=', allocated(c)
  end subroutine p
end module m2

program main
  use m, only : a
  use m2, only: p
  implicit none

  allocate(a(3,3))
  write(*,*) 'allocated?=', allocated(a)
  call p(a)

end program main

The output:

allocated?= T 
allocated?= F 

The first is as expected, but why the allocated status becomes false, as is indicated by the second output?


Solution

  • Allocatable dummy arguments that have intent(out) are automatically deallocated when the procedure is entered according to thevstandard. The intent also affects the allocation status, not just the values inside.

    It actually makes a very good sense. If it is intent(out), any previous allocation status should not matter.