5

Consider the following Fortran program:

program test
character(len=:), allocatable :: str
allocate(character(3) :: str)
print *, len(str)
str = '12345'
print *, len(str)
end program

When I run this I get the expected result:

   3
   5

That is, the character string was resized from 3 to 5 when str was set to '12345'. If, instead, I use an array of dynamic strings this is not true. Example:

program test
character(len=:), allocatable :: str(:)
allocate(character(3) :: str(2))
print *, len(str(1)), len(str(2))
str(1) = '12345'
print *, len(str(1)), len(str(2))
end program

When I run this I get:

   3           3
   3           3

So the set of str(1) did not change the length the string. I get the same behavior with ifort 16.0.2 and gfortran 5.3.1. My question is this behavior consistent with the latest Fortran standard or is this a bug in the compilers?

3
  • which compilation flags did you use? Try to set boundary checking and warnings (options like -C and -Wall) Commented May 9, 2018 at 14:42
  • Each element in an allocatable array of strings has the same length. To get an allocatable array of allocatable strings, you can use the technique shown here. Commented May 9, 2018 at 14:57
  • @albert: No flags were used. See the answer as to why this is the way it is. Commented May 10, 2018 at 17:54

2 Answers 2

5

This is the correct behaviour. An element of an allocatable array is not itself an allocatable variable and cannot be re-allocated on assignment (or in any other way). Also, all array elements must have the same type - including the string length.

Sign up to request clarification or add additional context in comments.

Comments

1

Expanding on @Vladimir F's answer, you could achieve what you have in mind with a few changes to your code, like the following (which creates a jagged array of character vectors):

program test

type :: CherVec_type
    character(len=:), allocatable :: str
end type CherVec_type

type(CherVec_type) :: JaggedArray(2)

allocate(character(3) :: JaggedArray(1)%str)
allocate(character(3) :: JaggedArray(2)%str)
print *, len(JaggedArray(1)%str), len(JaggedArray(2)%str)

JaggedArray(1)%str = "12345"
print *, len(JaggedArray(1)%str), len(JaggedArray(2)%str)

end program

which creates the following output:

$gfortran -std=f2008 *.f95 -o main
$main
       3           3
       5           3

1 Comment

This is similar to the difference between having a "pointer to an array" (the original post) as opposed to having an "array of pointers" (this post).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.