我有一个子程序,本质上是一个记录器。它接受一个必需的字符串,以及它格式化的两个可选参数。
这是一个简化版本。目前,写入
action_local
时会失败
subroutine log(required_param, action, idx)
character(len=*), intent(in) :: required_param
character(len=*), intent(in), optional :: action
integer, intent(in), optional :: idx
character(:), allocatable :: action_local
10 format(A, A, I)
if (present(action) .and. present(idx)) then
write(action_local, 10) ' ', action, idx ! fails: action_local is not allocated
else
action_local = ''
end if
print *, required_param // action_local
end subroutine
理想情况下,我不会猜测所需的大小 - 我只是让 write 语句的输出分配它需要的大小。有没有办法在不提前分配的情况下写入可分配的
character
?
从这个来源看来这可能是不可能的。示例代码在修剪之前分配适当大量的空间。
在函数名称返回字符值的情况下,没有需要长度匹配的实际参数,因此通常最好将函数名称声明为具有可分配的长度。如果值是在赋值语句中分配的,则不需要其他任何操作,但如果它从 I/O 操作获取值,则可能需要首先分配其长度(或者首先写入临时固定长度字符串)。
function int_to_string(intval) result (funcname)
integer, intent(in) :: intval
character(len=:), allocatable :: funcname
! initially allocate enough length for largest possible integer
allocate(character(len=12) :: funcname)
write(funcname, '(i0)') intval
! then reallocate
funcname = trim(funcname)
end function int_to_string
在这种情况下,
! allocate enough space for action plus integer plus space
allocate(character(len=len(action) + 13) :: action_local)