数组和指针形状

sun*_*mat 4 arrays fortran pointers

有人可以解释为什么以下程序不起作用,以及如何使其工作?在主程序中我分配了一个指针,在子程序中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
Run Code Online (Sandbox Code Playgroud)

输出:

 In test:            3           5           7
 In sub:     12694064           1           3
 Back in test:            3           5           7
Run Code Online (Sandbox Code Playgroud)

谢谢

PS:我正在使用gfortran(gcc 4.4.3)

编辑:使用gfortran 4.6,这段代码根本无法编译.我收到错误:

在(1)处的过程'sub'的虚拟参数'arr'具有需要该过程的显式接口的属性

M. *_* B. 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
Run Code Online (Sandbox Code Playgroud)