简体   繁体   English

在 Fortran 中返回不同长度的字符串数组

[英]Return an array of strings of different length in 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.我想创建一个类型来包含 Fortran 中的字符串数组,而无需显式分配长度,以便我可以从函数中返回它。

The following is my type:以下是我的类型:

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

The following is the function's signature:以下是函数的签名:

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?如何声明类型以便字符串可以具有不同的长度?

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.还需要在派生类型的数组中允许不同长度的灵活性。

However, using len=* is not the correct way to say "deferred length" (it is "assumed length").但是,使用len=*不是说“延迟长度”(它是“假定长度”)的正确方法。 Instead, you may use len=: and make the component allocatable (or a pointer):相反,您可以使用len=:并使组件可分配(或指针):

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

Then one may have an array of returnArr objects:那么一个人可能有一个returnArr对象数组:

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

Assignment such as as赋值如

  j(1)%char = "Test"

then relies on automatic allocation of the component char .然后依赖于组件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

and allocate j(1) to a length different from j(2) (etc.).并将j(1)分配到与j(2)不同的长度(等等)。

Similarly相似地

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

doesn't allow those char component elements to be of different lengths.不允许这些char组件元素具有不同的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM