Allocatable arrays in Fortran90

 

If you are writing this lab in Fortran, allocatable arrays may be useful. Here is a toy example that shows how it works:

program alloc
  integer :: n
  double precision, allocatable, dimension(:, :) :: A

  do n = 10, 100, 10
    allocate(A(n, n))      ! allocate an nxn-matrix

    call random_number(A)  ! work with A ...
    print*, A(1, 1)        ! or whatever

    deallocate(A)          ! free the space
  end do

end program alloc

dimension(:, :) means that we have a two-dimensional array. dimension(:) would be a one-dimensional array etc.

There is a more general allocate-statement that is useful if we want to see if there is enough memory available to allocate the matrix. The way we have written the program it will crash if we ask for too much memory, as in the following lines of code:

  n = 100000
  allocate(A(n, n))      ! allocate an nxn-matrix, 74.5 Gbyte
  A = 0.0
  deallocate(A)          ! free the space


Back