I have a code where I set up a character array with set of default "options", which I may or may not wish to overwrite during the code execution. If I initialize the array with strings of all the same length (shorter or equal to the maximum possible length of 5), then the code works:
PROGRAM test
character(len=5) :: s(3)=["a","b","c"]
s(1)="12345678"
print *,s
END PROGRAM test
output
12345b c
But if the strings are variable lengths.
character(len=5) :: s(3)=["a","bb","c"]
Then I get a compilation error:
Error: Different CHARACTER lengths (1/2) in array constructor at (1)
I can get it to work by padding with spaces to make all string equal like this
character(len=5) :: s(3)=["a ","bb","c "]
But that is a bit tedious for my actual example as I have some very long strings, so it is a lot of space-bar-pressing-while-counting-out-loud... Is there a way to inititalize character arrays with variable length variables, i.e. some kind of auto padding?
You need to manually specify the type-spec in the array constructor, as
character(len=5) :: s(3) = [character(len=5) :: "a", "bb", "c"]
this will convert each element in the array to same type, character(len=5)
, such that the array constructor is legal.