2012-02-21 103 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