Menu Close

ALLOCATE (Dynamic Memory) in FORTRAN

In Fortran, you can allocate memory dynamically using the ALLOCATE statement. The ALLOCATE statement is used to allocate memory for arrays, derived types, or other variables at runtime.

Here’s the general syntax for allocating memory in Fortran:

ALLOCATE (array_name(dimensions), [STAT=stat_variable,] [ERRMSG=error_message])
  • array_name: The name of the array or variable you want to allocate.
  • dimensions: The size or shape of the array. For example, if you want to allocate a one-dimensional array of size 100, you can specify dimensions(100).
  • STAT=stat_variable: Optional. A variable that will contain the allocation status. If the allocation is successful, stat_variable will be set to zero. If there is an error, stat_variable will be set to a nonzero value.
  • ERRMSG=error_message: Optional. A character variable that will contain an error message if the allocation fails.

 

Example (how to allocate a one-dimensional array in Fortran):

program allocate_example
  implicit none

  integer, allocatable :: my_array(:)
  integer :: i, size, stat
  size = 100

  allocate(my_array(size), stat=stat)

  if (stat /= 0) then
    write(*,*) "Allocation failed!"
    stop
  else
    write(*,*) "Allocation successful!"
  end if

  ! Use the allocated array here

  deallocate(my_array) ! Free the allocated memory

end program allocate_example


More Related Stuff