3

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.

Ian Bush
  • 6,996
  • 1
  • 21
  • 27
Kieran
  • 123
  • 1
  • 10
  • 2
    Please provide detail on how the arrays would be specified by the file and used. You have one answer guessing about the structure (several rank-1 arrays each of which can be referenced as an element of a containing rank-1 array) you have, but for a more precise guide we need to know more from you. – francescalus Mar 13 '22 at 21:40
  • 2
    Some people read the file first, allocate the arrays, rewind the file, and read that file into the arrays the second time around. – Holmz Mar 14 '22 at 07:36
  • 1
    @francescalus Holmz Thank you for your suggestions. I think that I veryreverie had already provided a useful sample structure to me. I learned a lot. Thank you again. – Kieran Mar 14 '22 at 08:59

1 Answers1

2

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
veryreverie
  • 2,871
  • 2
  • 13
  • 26
  • 1
    Thank you very much for the sample structure. It is truly helpful to me. Thank you again. – Kieran Mar 14 '22 at 09:00