0

consider the following code:

program test

implicit none

integer :: i
integer, parameter :: N=6
integer :: inx(0:N-1)

type a2
 integer, pointer :: xp(:)
end type a2

type(a2), allocatable :: new(:)


allocate(new(0:N-1))

inx=[2, 2, 0, 3, 6, 5]


do i=0,N-1  

  if (inx(i)==0)  then 
    allocate(new(i)%xp(inx(i))); new(i)%xp(inx(i))=i
    print*, 'i, new%xp(i)=', i,  new(i)%xp(inx(i))
  end if
end do 


end program test

When I run this with gfortran I get the following error: At line 28 of file test.f90 Fortran runtime error: Index '0' of dimension 1 of array 'new%xp' below lower bound of 1

which I am having trouble understanding. Why is the component xp of new not allowed to have index 0?

geom
  • 195
  • 8
  • Where do you specify that `new%xp` has a lower bound of zero? If you think `allocate(x(0))` (say) gives `x` a lower bound of 0, it doesn't. – francescalus Oct 21 '22 at 19:56
  • More precisely, such an array is zero size (it has no element) and hence any index is out of bounds. – PierU Oct 21 '22 at 20:11
  • For `i=3` it does, since `inx(3)=0` – PierU Oct 21 '22 at 21:34
  • For `i=2`, `inx(2)=0`, so `allocate(new(i)%xp(inx(i)))` should give `new(2)%xp(0)`, but I get the error message shown above – geom Oct 21 '22 at 22:09
  • 1
    As in my previous comment and the linked question, for `i` value 2, the allocation `allocate(new(2)%xp(0))` does not give an array with element `new(2)%xp(0)`. The array has lower bound 1, upper bound 0, and size 0. It has no elements. – francescalus Oct 21 '22 at 22:28
  • (indeed the problem if for `i=2`, I missed the fact that `inx` was a static array) – PierU Oct 22 '22 at 12:29

0 Answers0