Fortran 90: Dynamic Memory

The size of arrays can now be specified at run time.

Here's how a typical Fortran 77 program would manage an array whose size could vary at run time.

integer inmax
parameter (inmax=100)
real*8 array(inmax)
.
.
!Some part of the code determines nmax
.
if (nmax.gt.inmax) then
print*,'error: nmax.gt.inmax',nmax,inmax
stop
endif
If nmax is too small, the parameter statement must be changed and the code recompiled.

Now, this same example with an allocatable array

integer :: inmax,error
real*8, allocatable :: array(:)
.
.
!Some part of the code determines nmax
allocate(array(nmax),stat=error)
if (stat.ne.0) then
print*,'error: couldn't allocate memory for array, nmax=',nmax
stop
endif
In this version the size of array is limited only by the size of available memory. Additionally, only the memory needed is actually used (compared with the old method, where array is always size inmax, no matter how much is used.) To release this memory, use the deallocate statement.
deallocate(array,stat=error)
if (error.ne.0) then
print*,'error in deallocating array'
endif

Pointers

An array can be declared as a pointer (just like allocatable). A pointer can be used in an allocate statement just as if it had been declared allocatable. Pointers seem to be needed in order to pass assumed shape arrays.

For instance,let us allocate an array in the main program and pass it to a subroutine.

program pointer
   real*8, pointer  :: array(:,:)

interface
   subroutine sub(array)
      real*8, pointer :: array(:,:)
   end subroutine
end interface

    allocate(array(4,4))
    call sub(array)
    end

end program

subroutine sub(array)
  real*8, pointer :: array(:,:)

The interface block seems to be necessary to pass the array correctly.


Return to Fortran 90 index