在子程序调用期间保持 Fortran 中的数组限制
我有以下程序
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
数组的编号必须与调用方中的编号相同?
I have the following program
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
In the line marked with "here" I am doing something wrong. The fact is that when I receive the array a
(in the caller allocated from -5 to +5), the callee uses conventional numbering (1 to n), meaning that assigning -4 I am doing an out of boundary assignment. How can I instruct the compiler that, within the bar
routine, the numbering of the a
array must be the same as in the caller ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在子例程中使用的虚拟参数类型(尺寸用冒号指定)称为“假定形状”。这个名字就是线索——Fortran 只传递形状,而不传递下限和上限。下限被假定为 1,除非您按照 kemiisto 的答案中所示覆盖它。如果下限不固定,您可以传递一个参数作为下限。
稍后添加:如果编译时不知道较低维度的代码示例:
The type of dummy argument that you are are using in the subroutine, with the dimension specified with a colon, is called "assumed shape". This name is the clue -- Fortran passes only the shape and not the lower and upper bounds. The lower bound is assumed to be one unless you override it as shown in the answer by kemiisto. If the lower bound is not fixed, you can pass an argument to use as the lower bound.
Later addition: a code example if the lower dimension isn't known at compile time:
有两个常见的选项:
There are two common options:
不确定,但根据标准,您可以指定假定形状数组的下限。
Not sure but according to the standard you can specify the lower bound for an assumed-shape array.