数组和指针形状 [英] Array and pointer shapes
问题描述
谁能解释一下为什么下面的程序不起作用,以及如何使它起作用?在主程序中我分配了一个指针,在子程序 sub
中我查找数组的形状并得到错误的值.
Can someone explain me why the following program doesn't work, and how to make it work?
In the main program I allocate a pointer, in the subroutine sub
I look for the shape of the array and get wrong values.
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)
PS: I'm using gfortran (gcc 4.4.3)
使用 gfortran 4.6,此代码根本无法编译.我得到了错误:
with gfortran 4.6, this code simply doesn't compile. I get the error:
(1) 处的过程 'sub' 的伪参数 'arr' 有一个属性,该属性需要此过程的显式接口
Dummy argument 'arr' of procedure 'sub' at (1) has an attribute that requires an explicit interface for this procedure
推荐答案
要使用 Fortran 90/95/2003/2008 的高级"功能,调用者应该知道过程的接口(子例程和函数).这称为显式"接口.gfortran 4.6 告诉你问题出在哪里.最简单的方法是将您的程序放在一个模块中.试试这个:
To use the "advanced" features of Fortran 90/95/2003/2008 the interfaces of procedures (subroutines and functions) should be known to the caller. This is called "explicit" interfaces. gfortran 4.6 told you what the problem was. The easiest way is to put your procedures in a module. Try this:
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
这篇关于数组和指针形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!