Are there problems with using gear arrays in Fortran with multiple distribution levels?

In my Fortran code, I want to use jagged arrays with multiple distribution levels. The sample code that I mean is

module nonsquare_matrix_mod
implicit none

   type :: nonsquare_matrix 
      integer :: d
      real*8, dimension(:), allocatable :: vector
   end type nonsquare_matrix

   type(nonsquare_matrix),dimension(:),allocatable :: mymatrix

end module nonsquare_matrix_mod

program nonsquare_matrix_test
   use nonsquare_matrix_mod
   implicit none

integer, parameter :: max_size=50
integer :: i

allocate(mymatrix(max_size))
do i=1,max_size
    allocate(mymatrix(i) % vector(i))
end do

print *, "allocated"


end program

I want to implement this programming strategy to save memory. I know that the memory saved in this example is not too large, but for my actual project I work with much larger data structures. I was wondering if there are any dangers in this programming practice, such as data that is not stored permanently or is more prone to memory leaks. Or is it a useful way to save memory without many flaws? Thank.

+5
source share
1 answer

, , . , . :

  • . , , , .

  • allocate . (, ), , "" .

  • ( ), .

( , ), , , :

 program nonsquare_matrix_test
  implicit none

  integer, parameter :: dp = kind(1.0d0)
  integer, parameter :: maxlines = 50
  integer, parameter :: maxelements = 5000
  real(dp), allocatable :: buffer(:)
  integer, allocatable :: rowindex(:)
  integer :: ii

  allocate(buffer(maxelements))
  allocate(rowindex(maxlines + 1))
  rowindex(1) = 1
  do ii = 1, maxlines
    rowindex(ii + 1)  = rowindex(ii) + ii
  end do
  ! ...  
  ! Omitting the part which fills up the array
  ! ...
  ! Accessing a given line (e.g. line 5)
  print *, "Content of line 5:"
  print *, buffer(rowindex(5):rowindex(6)-1)

end program nonsquare_matrix_test
+6

All Articles