2012-02-21 141 views
4

有人可以解釋爲什麼下面的程序不工作,以及如何使它工作? 在主程序中我分配一個指針,在子程序sub中查找數組的形狀並得到錯誤的值。陣列和指針形狀

program test 
    real, pointer, dimension(:,:,:) :: arr 
    allocate(arr(3,5,7)) 
    print *, "In test: ",shape(arr) 
    call sub(arr) 
    print *, "Back in test: ",shape(arr) 
    end program test 

    subroutine sub(arr) 
    real, pointer, dimension(:,:,:) :: arr 
    print *, "In sub: ",shape(arr) 
    end subroutine 

輸出:

In test:   3   5   7 
In sub:  12694064   1   3 
Back in test:   3   5   7 

感謝

PS:我使用gfortran(GCC 4.4.3)

編輯:與gfortran 4.6,該代碼根本不編譯。我得到的錯誤:

Dummy argument 'arr' of procedure 'sub' at (1) has an attribute that requires an explicit interface for this procedure

回答

9

要使用的Fortran 90/95/2003/2008的「高級」功能的程序(子程序和函數)的接口應該知道給調用者。這被稱爲「顯式」接口。 gfortran 4.6告訴你問題是什麼。最簡單的方法是將你的程序放在一個模塊中。試試這個:

module mysubs 
implicit none 
contains 
    subroutine sub(arr) 
    real, pointer, dimension(:,:,:) :: arr 
    print *, "In sub: ",shape(arr) 
    end subroutine 
end module mysubs 

program test 
    use mysubs 
    implicit none 
    real, pointer, dimension(:,:,:) :: arr 
    allocate(arr(3,5,7)) 
    print *, "In test: ",shape(arr) 
    call sub(arr) 
    print *, "Back in test: ",shape(arr) 
end program test