Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Fortran Dynamic Allocation Array

Hadi_S_
Beginner
1,254 Views

Hi

the problem is that How can i increase a (Fortran) allocated array size in a program?

in program like this:

...
real(8), allocatable, dimension(:) :: x
...
! programs body
N=100
allocate(x(N))
...
N=150
allocate(x(N)) ! but this is an error

there is two approach

First: using move_alloc

Second: using x=[x,(x(1),i=1,j-size(x))]

but x can be a class type array in bellow program you can see usage of two approaches in two loops.

I compare every approach for time cost and see second takes more time.

as Steve point that: in 2nd approach because x is used on both sides of the assignment, the compiler has to create a temporary for the array constructor before assigning to the left side, thus two copies. I don't see any good way to avoid a copy as it's very unlikely that the space after the existing array is unallocated. You can avoid making two copies, though, with suitable use of MOVE_ALLOC and initializing only the expanded elements.

!$ cat 
program realloc 
use iso_fortran_env, only : real64 
implicit none 
integer :: i,N,j 
integer, parameter :: wp=real64 

type math 
    real(wp) :: x1 
    real(wp) :: y1 
end type 

type(math), allocatable, dimension(:) :: h, temp 

N=10 
allocate(h(N)) 
h(:)%x1 = 1. 
h(:)%y1 = 2. 

do j=N, 100000 ! this loop takes 110 s (using GNU FORTRAN)
    allocate(temp(j)) 
    temp(1:size(h)) = h 
    call move_alloc(temp, h) 

    h(:)%x1 = 1. 
    h(:)%y1 = 2. 
    !print *,"size(h)=",size(h) 
end do 

do j=N, 100000 ! this loop takes 160 s (using GNU FORTRAN)
    h = [h,(h(1),i=1,j-size(h))] 

    h(:)%x1 = 1. 
    h(:)%y1 = 2. 
    !print *,"size(h)=",size(h) 
end do 

end program

so question: Intel(R) Visual Fortran Compiler XE 13.1.0.149 can run second approach but the dimension does not increase without any error.

and second approach is not really suitable? is really  move_alloc the best way? does it works using pointer and somethings?

Thanks

0 Kudos
2 Replies
Arjen_Markus
Honored Contributor II
1,254 Views

You need to specify the option /assume:realloc_lhs, as otherwise the automatic reallocation on assignment does not work

0 Kudos
FortranFan
Honored Contributor III
1,254 Views

Look into compiler options of /assume:realloc_lhs as well as /standard-semantics (a more expanded option set that includes realloc_lhs) closely and see what matches closely with your needs.

Note the use of MOVE_ALLOC can give a coder better control in resizing arrays (both increasing as well as decreasing the size) and allow the placement of existing values as desired in the new array with a single copy operation.

0 Kudos
Reply