2016-11-17 64 views
0

我不是一個很好的程序員,我只是試圖與提供數據作爲指針的模型進行接口。這些指針在寫入數據之前通過幾個子例程傳遞。我不知道如何做到這一點,以避免內存泄漏。正確的方法將指針傳遞到許多子例程

比方說,我有一個數組指針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 
+1

我不完全相信你所問的,但如果你有你的代碼中的問題很可能涉及到'意圖(出)'屬性這些指針。例如,請參閱[此相關問題](https://stackoverflow.com/q/29737367)。或者所謂的_explicit shape_ nature(與指針衝突)。 – francescalus

+1

您只需指定尺寸一次。在子程序中,你應該聲明一個: '真實的,指針,維度(:, :),意圖(out):: a'。 (A)'後,如果你不再需要指針,你可以'廢除(A)' –

回答

1

請注意,你的代碼是不是Fortran語言90. intent屬性對於那些在2003年的Fortran

介紹了虛擬指針(正式的)參數的intent指指針的關聯狀態,而不是它的目標。另外,如果參數是具有 指針組件的派生類型,則intent將應用於類型對象本身,而不是指針的目標。即,如果,例如,使用intent(in),數據區指針的對象是可以被修改:

module MyType_mod 

    implicit none 
    private 

    type, public :: MyType 
    integer, pointer :: ptr(:) 
    contains 
    procedure :: sub => my_type_sub 
    end type MyType 

contains 

    subroutine my_type_sub(self) 
    ! Dummy argument 
    class(MyType), intent(in) :: self 

    ! The following is perfectly legal, 
    ! even though intent(in) was specified 
    self%ptr = 42 

    end subroutine my_type_sub 

end module MyType_mod 

program main 

    use MyType_mod, only: & 
     MyType 

    implicit none 

    type(MyType) :: foo 
    integer  :: alloc_stat 

    allocate(integer :: foo%ptr(100), stat=alloc_stat) 
    call foo%sub() 

end program main 

儘管不是必需的,在一個情況下,在前面的例子如,最好是狀態intent(inout)向讀者指示正在發生數據修改。

在另一方面,你會發現這個答案有用Fortran subroutine returning wrong values

+0

聲明「我不是一個很好的程序員」似乎有違使用指針。即使是真正優秀的程序員也經常爲各種原因避免使用指針。很難理解爲什麼要使用所提供代碼中的指針。即使使用指針是一個有趣的問題,我也會重新考慮是否需要指針。 – Holmz