[英]Pass Common block array size to subroutine in Fortran
I would like to pass the array dimension as a dummy variable to a subroutine. 我想将数组维度作为虚拟变量传递给子例程。 The array itself is on a common block. 数组本身在一个公共块上。 Here is the code: 这是代码:
PROGRAM test
integer i, nn
integer PARAMETER(Nt=10)
real x(Nt), y(nt), z(Nt)
Common /Bdat/ z
nn=Nt
do i=1,Nt
x(i)=i+1
z(i)=i-1
enddo
call estimate(x,y,nn)
print*, y
return
end
subroutine estimate(x,y,jj)
integer i,jj
real x(jj), y(jj), zq(jj)
COMMON /Bdat/ zq
do i=1, jj
y(i)=x(i)+zq(i)
enddo
return
end
this is the error I get from the subroutine: 这是我从子程序得到的错误:
real x(jj), y(jj), zq(jj)
1
Error: Variable 'jj' at (1) in this context must be constant 错误:在这种情况下,(1)处的变量“ jj”必须恒定
I would really appreciate it if anybody could solve the issue. 如果有人能解决这个问题,我将不胜感激。
You have a scope problem. 您遇到范围问题。 Read: Scope in Fortran . 阅读: Fortran中的Scope 。 That is, your subroutine estimate
needs access to the variable Nt
which you need to pass as an additional argument, or you can move the entire subroutine inside your program using the contains
statement. 也就是说,您的子例程estimate
需要访问变量Nt
,您需要将其作为附加参数传递,或者您可以使用contains
语句在程序内移动整个子例程。 This will allow your program to run successfully, but I highly encourage you to abstain from using common
blocks. 这将使您的程序成功运行,但是我强烈建议您不要使用common
块。 If you cannot avoid them due to legacy codes see: Improve your FORTRAN 77 programs using some Fortran 90 features 如果由于遗留代码而无法避免使用它们,请参阅: 使用某些Fortran 90功能改进FORTRAN 77程序
Try using modules instead: 尝试改用模块:
module bdat
implicit none
private
public :: NT, z
integer, parameter :: NT = 10
real :: z(NT)
end module bdat
module my_sub
use bdat, only: &
zq => z ! You're free to rename the variable
implicit none
private
public :: estimate
contains
subroutine estimate(x,y)
! calling arguments
real, intent (in) :: x(:)
real, intent (out) :: y(:)
! local variables
integer :: i, jj
jj = size(x)
do i=1, jj
y(i)=x(i)+zq(i)
end do
end subroutine estimate
end module my_sub
program test
use bdat, only: &
NT, z
use my_sub, only: &
estimate
implicit none
integer :: i
real :: x(NT), y(NT)
do i=1,NT
x(i)=i+1
z(i)=i-1
end do
call estimate(x,y)
print *, y
end program test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.