2017-06-06 119 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'擺脫了我的錯誤。 –

相關問題