Is there any existing way to emulate growing array in Fortran? Like vector in C++. I was very surprised when I haven't found anything on this subject on the Internet.
As a motivation example, suppose I compute some recurrence relation and I want to store all the intermediate numbers I get. My stopping criterion is the difference between adjacent results so I cannot know beforehand how much memory I should allocate for this.
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
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 elementsn
grows above the size of the arraysize(a)
you can allocate a new array larger by some factor (here 2x) and copy the old elements there. There is norealloc()
in Fortran, unfortunately.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.