I am sure it has been shown somewhere on this site before, but I cannot find it.
First, in Fortran 2003, you can add one element by simple
a = [a, item]
as commented by francescalus. This is likely to reallocate the array very often and will be slow.
You can keep your array to be allocated to somewhat larger size then your number of elements n
. When your number of elements n
grows above the size of the array size(a)
you can allocate a new array larger by some factor (here 2x) and copy the old elements there. There is no realloc()
in Fortran, unfortunately.
module growing_array
implicit none
real, allocatable :: a(:)
integer :: n
contains
subroutine add_item(item)
real, allocatable :: tmp(:)
real, intent(in) :: item
if (n == size(a)) then
!this statement is F2003, it can be avoided, but I don't see why in 2016
call move_alloc(a, tmp)
allocate(a(n*2))
a(1:n) = tmp
end if
n = n + 1
a(n) = item
end subroutine
end module
I left out the initial allocation, it is simple enough.
It all can be put into a derived type with type-bound procedures, and use it as a data structure, but that is pure Fortran 2003 and you wanted 90. So I show Fortran 95, because Fortran 90 is flawed in many ways for allocatable arrays and is desperately obsolete and essentially dead.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…