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 allocprogram alloc
  integer :: n
  double precision, allocatable, dimension(:, :) :: A, B

  n = 5
  allocate(A(n, n))      ! allocate an nxn-matrix. Index starts at 1.

! allocate (n+1) x (n+1) elements,
! B(0, 0), ..., B(0, 5)
!          ...
! B(5, 0), ..., B(5, 5)

  allocate(B(0:n, 0:n))

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

  call random_number(B)  ! work with B ...
  print*, B(0, :)        ! or whatever
  print*, B(n, 0)

  deallocate(A)          ! free the space
  deallocate(B)          ! free the space

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