我有以下程序
module test
contains
subroutine foo()
integer, allocatable :: a(:)
allocate(a(-5:5))
call bar(a)
print *, a
end subroutine
subroutine bar(a)
integer, intent(out) :: a(:)
a = 0
a(-4) = 3 ! here
a(2) = 3
end subroutine
end module
program x
use test
call foo()
end program
在标有“这里”的行中,我做错了什么。事实是,当我收到数组
a
时(在从 -5 到 +5 分配的调用者中),被调用者使用常规编号(1 到 n),这意味着分配 -4 我正在执行越界分配。我如何指示编译器在 bar
内例程,a
的编号数组必须与调用者中的相同吗?
最佳答案
您在子例程中使用的虚拟参数类型,其维度用冒号指定,称为“假定形状”。这个名字就是线索——Fortran 只传递形状而不是上下限。下限假定为 1,除非您按照 kemiisto 的回答中所示覆盖它。如果下限不固定,您可以传递参数以用作下限。
后来添加:如果在编译时不知道较低维度的代码示例:
subroutine example (low, array)
integer, intent (in) :: low
real, dimension (low:), intent (out) :: array
关于arrays - 在子程序调用期间保持 Fortran 中的数组限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4366495/