英文:
Why an allocated array gets unallocated when it is passed to a subroutine?
问题
The first output "allocated?= T" is as expected, indicating that the allocatable array a
in the main
program is allocated, which means it has been dynamically allocated memory.
The second output "allocated?= F" in the subroutine p
indicates that the allocatable array c
passed as an actual argument to the subroutine is not allocated. This can happen for a couple of reasons:
-
The subroutine
p
specifies theintent(out)
attribute for the dummy argumentc
. When a dummy argument is declared withintent(out)
, it means that the subroutine is expected to allocate the memory for the argument. In this case, the subroutinep
does not allocate memory forc
, which is why it reports that it's not allocated. -
In the main program, when you call
p(a)
, you pass the allocatable arraya
to the subroutine. If the subroutinep
modifiesc
in a way that deallocates it or assigns it to a different memory location, it can result in the allocated status ofc
becoming false. Without seeing the actual code inside the subroutine, it's challenging to pinpoint the exact reason for the deallocation.
If you want c
to be allocated within the subroutine p
, you should modify the subroutine declaration to remove intent(out)
like this:
subroutine p(c)
implicit none
real, allocatable :: c(:,:) ! Remove 'intent(out)'
write(*,*) 'allocated?=', allocated(c)
end subroutine p
This change will make the subroutine allocate memory for c
, and the allocated status should be true when the subroutine is executed.
英文:
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?
答案1
得分: 2
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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论