角色元素功能。给参数作为char-length参数?

时间:2016-07-10 13:28:01

标签: function interface fortran

问题是,当我将integer charlen 作为字符元素函数的长度定义传递时,我会收到错误消息real program chararr implicit none !! integer,parameter :: charlen = 20 !! interface character(len=20) elemental function adjR(a) character(len=*),intent(in) :: a end function end interface !! character(charlen) :: test(3), testR(3) test = ["hej", "hoj", "haj"] testR = adjR(test) print*, test print*, testR end program character(20) elemental function adjR(a) character(len=*),intent(in) :: a adjR = adjustr(a) end function 。更具体地说,下面的 MWE 有效

integer,parameter :: charlen = 20

但是行character(len=charlen) elemental function adjR(a) 什么也没做。当我改变像这样的函数和接口定义

charmin.f90:7:14:

 character(len=charlen) elemental function adjR(a)
              1
Error: Expression at (1) must be of INTEGER type, found REAL

我收到以下错误:

program chararr
use char_mod, only: charlen, adjR
implicit none
!!
!interface
!character(30) elemental function adjR(a)
!character(len=*),intent(in) :: a
!end function
!end interface 
!!!
character(charlen) :: test(3), testR(3)

test = ["hej", "hoj", "haj"]
testR = adjR(test)


print*, test
print*, testR
print*, charlen !!! it is here
end program 

更新

亚历山大的解决方案是代码:

charmin.f90:

module char_mod

implicit none
integer,parameter :: charlen = 30

private
public charlen, adjR

contains

character(charlen) elemental function adjR(a)
implicit none
character(len=*),intent(in) :: a
adjR = adjustr(a)
end function

end module

char_mod.f90:

gfortran -c char_mod.f90 
gfortran charmin.f90 char_mod.f90 -o program

编译:

jonessal

1 个答案:

答案 0 :(得分:1)

charlen在程序范围内定义,但函数adjR超出了该范围。因此,charlen无法访问,并且由于函数没有定义implicit none,因此它被解释为实数变量。

对此的一个解决方案是将adjR放入模块中,并使charlen成为模块变量。