Fortran increase dynamic array size in function

前端 未结 3 1068
滥情空心
滥情空心 2020-12-30 13:28

I need a variable size array in Fortran. In C++ I would use vector. So I have a function like

integer function append(n, array, value)
  integer, pointer, d         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 14:03

    OK, the problem is that you cannot deallocate and re-allocate the array that you are assigning a function value to. You are correct about the cause of your problem (arguments passed by reference and not by value as it is in C). Since you deallocate the array inside the function body, the assignment to that array becomes invalid, leading to segfault. This is not a gfortran issue, tried it with ifort and pgf90, all of them report the same problem. This works for me:

    PROGRAM dynamic_size
    INTEGER,DIMENSION(:),ALLOCATABLE :: array
    
    ALLOCATE(array(10))
    
    array=(/1,2,5,7,4,3,6,5,6,7/)
    
    WRITE(*,*)SIZE(array)
    CALL resize_array
    WRITE(*,*)size(array)
    
    CONTAINS
    
    SUBROUTINE resize_array
    INTEGER,DIMENSION(:),ALLOCATABLE :: tmp_arr
    
    ALLOCATE(tmp_arr(2*SIZE(array)))
    tmp_arr(1:SIZE(array))=array
    DEALLOCATE(array)
    ALLOCATE(array(size(tmp_arr)))
    array=tmp_arr
    
    ENDSUBROUTINE resize_array
    
    ENDPROGRAM dynamic_size
    

提交回复
热议问题