Building up N allocatable arrays

Viewed 71

I want to build up a number (N) of allocatable array but the total number of these arrays and the size of each array are not known beforehand. These information can only be read from the file.

Is there any way to read N and size of each array from the file; and then, build up such N allocatable arrays in Fortran code automatically?

Any suggestion/hint is appreciated.

1 Answers

You need a "jagged 2D array", something which Fortran does not support natively. Instead, you can build one yourself using a user-defined type which contains an array. For example,

module arrays
  implicit none
  
  type :: Array1D
    integer, allocatable :: contents(:)
  end type
  
  type :: Array2D
    type(Array1D), allocatable :: contents(:)
  end type
end module

Then your program would look something like

type(Array2D) :: foo
integer :: N,M
integer :: i

! Read `N` from the file.
N = ...
allocate(foo%contents(N))
do i=1,N
  ! Read the size of the i'th array from the file.
  M = ...
  allocate(foo%contents(i)%contents(M))
  ! Read the i'th array from the file.
  foo%contents(i)%contents = ...
enddo
Related