Search code examples
gdbfortranderived-typesallocatable-array

Fortran: Allocatable array of derived type containing an array of derived type


I am currently working on a large Fortran program where I have a discrete numerical grid that contains a series of particles that I track within the bounds of the grid. To do this I have defined the following three derived types:

type :: particle
    real(pr), dimension(3) :: r = 0.0_pr ! position
    real(pr), dimension(3) :: p = 0.0_pr ! momentum
end type particle

type :: rcell ! position cell
    integer, dimension(6) :: bpoints = 0 ! cell grid points
    integer :: np = 0 ! number of particles in cell
    type(particle), dimension(50) :: parts ! particles in cell
end type rcell

type :: pcell ! momentum cell
    integer, dimension(6) :: bpoints = 0 ! cell grid points
    integer :: np = 0 ! number of particles in cell
end type pcell

...

type(rcell), dimension(:), allocatable :: rbin ! position space bins
type(pcell), dimension(:), allocatable :: pbin ! momentum space bins

...

allocate(rbin(100))
allocate(pbin(100))

First of all, is this an acceptable use of derived types (i.e. having an allocatable array of a derived type that contains an array of a derived type)? The code compiles fine using gfortran 4.8.3.

However, I encounter some strange issues when trying to debug the code using gdb 7.7.1 under Fedora. When trying to look at the data in an element of the rbin array (using print rbin(10)%bpoints for example) gdb always prints out (0, 0, 0, 0, 0, 0) even though I have assigned data to bpoints (e.g. rbin(10)%bpoints = (/1,2,1,2,1,2/)). If I look at the data in an element of the pbin array using print pbin(10)%bpoints for example, then I get exactly what I expect. Does anyone have some insight on this issue?


Solution

  • I use these kinds of structures in my code all the time. No problem compiling or running under on linux-like OS using gfortran. The intel compiler had issues with this type of code 5 years ago, but I have moved away from that compiler lately so I'm not sure if they've caught up to the newer Fortran standards now. I use MPI, so I can rarely use gdb and can't be helpful about why its throwing errors.

    Anyway, I agree with Mark; modern Fortran (compiled using gfortran) can handle this type of structure just fine.