Fortran派生类型组件越界疑问:为何xp数组不允许使用索引0?
Fortran代码索引越界问题解答
问题描述
编写了如下Fortran测试代码,使用gfortran运行时出现索引越界错误,无法理解为何派生类型new的组件xp不允许使用索引0:
测试代码
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
运行错误信息
At line 28 of file test.f90 Fortran runtime error: Index '0' of dimension 1 of array 'new%xp' below lower bound of 1
问题原因与解决方法
- 核心原因:当
inx(i)=0时,allocate(new(i)%xp(inx(i)))分配了一个长度为0的数组。Fortran中默认数组的下界是1,长度为0的数组没有任何可访问的有效索引,此时尝试用索引0去访问必然触发越界错误。 - 解决方式:如果需要让数组
xp支持从0开始的索引,需在分配时显式指定数组的上下界。比如将分配语句修改为:
当allocate(new(i)%xp(0:inx(i)))inx(i)=0时,这个数组的范围是0:0,长度为1,索引0就成为了有效索引,可以正常赋值和访问。 - 额外说明:原代码中分配长度为0的数组本身没有实际意义,若不需要这种空数组,也可以直接跳过
inx(i)=0的情况,避免无意义的分配操作。
内容的提问来源于stack exchange,提问作者geom
相关产品推荐
相关产品推荐

