2017-06-06 20 views
2

我正在尝试编写一个类新过程,它为字符数组添加一个新字符,但不断在“数组构造函数中的不同字符长度”错误(使用GFortran编译),即使字符长度在我看到的情况下也是如此。添加到Fortran中的字符数组

这里是我的功能:

subroutine addToArray(this, newElement) 
    class(MyClass), intent(inout) :: this 
    character(len=*), intent(in) :: newElement 
    character(len=256) :: tempElement 
    character(len=256), dimension(:), allocatable :: temp 

    tempElement = newElement    ! Needed otherwise newElement is of the wrong size 
    allocate(temp(size(this%charArray)+1) ! Make the char array bigger by 1 
    temp = [this%charArray, tempElement] 
    call move_alloc(from=temp, to=this%charArray) 
end subroutine 

这将导致错误Fortran runtime error: Different CHARACTER lengths (538976288/256) in array constructor。但是,如果我打印len(this%charArray)len(tempElement),它们都是256个字符长。那么538976288从哪里来?

我通常使用类似myObject%addToArray('hello')的方式调用此过程。 this%charArray在类型定义中声明为character(len=256), dimension(:), allocatable :: charArray,并使用allocate(this%charArray(0))进行分配。

+0

它可能是一个编译器错误。哪个gfortran版本?请注意,我们正在猜测MyClass的charArray组件的声明。请注意,Fortran 2003允许'this%charArray = [this%charArray,tmpElement]' – IanH

+0

如果使用gfortran,那么在不同版本中会出现很多类似的错误。只需搜索错误数据库。限制这些错误的一种方法是始终使用一个固定的字符长度。 –

+0

GFortran版本6.30。 charArray被声明为:'character(len = 256),dimension(:),allocatable :: charArray'并且它被分配了'allocate(this%charArray(0))'(澄清了问题)。 –

回答

0

看来它是我报GCC比去年同期https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70231

解决方法是优化至少-O1编译更多的错误。

如果不是相同的错误,需要包括编译标志和所有相关细节在内的确切再现情况。

+0

感谢弗拉基米尔,使用'-O1'摆脱了我的错误。 –