我不是一個很好的程序員,我只是試圖與提供數據作爲指針的模型進行接口。這些指針在寫入數據之前通過幾個子例程傳遞。我不知道如何做到這一點,以避免內存泄漏。正確的方法將指針傳遞到許多子例程
比方說,我有一個數組指針A
在寫入之前傳遞給幾個子例程,我該如何處理聲明,分配和釋放?
module data
implicit none
contains
subroutine s1(a)
real, pointer, intent(out) :: a(5,5)
call s2(a)
end subroutine s1
subroutine s2(a)
real, pointer, intent(out) :: a(5,5)
integer :: i
do i = 1,5
a(:,i) = 5.0
end do
end subroutine s2
end module data
Program test
use data, only : s1, s2
real, pointer, dimension(:,:) :: A => NULL()
allocate(A(5,5))
call s1(A)
write(*,*) A
deallocate(A)
end Program test
我不完全相信你所問的,但如果你有你的代碼中的問題很可能涉及到'意圖(出)'屬性這些指針。例如,請參閱[此相關問題](https://stackoverflow.com/q/29737367)。或者所謂的_explicit shape_ nature(與指針衝突)。 – francescalus
您只需指定尺寸一次。在子程序中,你應該聲明一個: '真實的,指針,維度(:, :),意圖(out):: a'。 (A)'後,如果你不再需要指針,你可以'廢除(A)' –