在Fortran中返回不同长度的字符串数组 [英] Return an array of strings of different length in Fortran

查看:95
本文介绍了在Fortran中返回不同长度的字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Fortran中创建一个包含字符串数组的类型,而无需显式分配长度,这样我就可以从函数中返回它.

I would like to create a type to contain an array of strings in Fortran without explicitly assigning lengths so I can return it from a function.

以下是我的类型:

type returnArr
    Character (*), dimension(4)  :: array
end type returnArr

以下是函数的签名:

type(returnArr) FUNCTION process(arr, mean, stdDev) result(j)

以下是我尝试设置结果的地方:

The following is where I try set the result:

j%array(1)= "Test"

但是我得到的只是以下错误:

But all I get is the following error:

Error: Character length of component ‘array’ needs to be a constant specification expression at (1)

如何声明类型,以使字符串的长度可以不同?

How can I declare the type so that the strings may be of different length?

推荐答案

派生类型的字符组件可能具有明确的长度,也可能具有其长度 deferred .后者是一个如何(通过多种方式)改变其值的方法.还必须在派生类型的数组中允许不同长度的灵活性.

A character component of a derived type may have either an explicit length, or it may have its length deferred. This latter is how one changes its value (by any of a number of means). It is also necessary to allow the flexibility of different lengths in an array of the derived type.

但是,使用 len = * 并不是说递延长度"的正确方法(它是假定长度").相反,您可以使用 len =:并使组件可分配(或指针):

However, using len=* is not the correct way to say "deferred length" (it is "assumed length"). Instead, you may use len=: and make the component allocatable (or a pointer):

type returnArr
  Character (:), allocatable  :: char
end type returnArr

然后可能会有一组 returnArr 对象:

Then one may have an array of returnArr objects:

function process(arr, mean, stdDev) result(j)
  type(returnArr) :: j(4)
end function

诸如以下的分配

  j(1)%char = "Test"

然后依靠组件 char 的自动分配.

then relies on automatic allocation of the component char.

请注意,现在函数结果是该容器类型的数组.我们不能做

Note that now the function result is an array of that container type. We cannot do

function process(arr, mean, stdDev) result(j)
  character(:), allocatable :: j(:)
end function

,然后将 j(1)分配给与 j(2)(等)不同的长度.

and allocate j(1) to a length different from j(2) (etc.).

类似地

type returnArr
  Character (:), allocatable  :: char(:)
end type returnArr

不允许这些 char 组件元素具有不同的长度.

doesn't allow those char component elements to be of different lengths.

这篇关于在Fortran中返回不同长度的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆