Return an array of strings of different length in Fortran

时光总嘲笑我的痴心妄想 提交于 2021-02-10 05:10:00

问题


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.

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?


回答1:


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"). Instead, you may use len=: and make the component allocatable (or a pointer):

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

Then one may have an array of returnArr objects:

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.

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.).

Similarly

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

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



来源:https://stackoverflow.com/questions/51968735/return-an-array-of-strings-of-different-length-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!