You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fortran分配含延迟长度数组的参数化派生类型数组失败求助

问题:分配含延迟长度的参数化派生类型数组失败

无法成功分配包含延迟长度数组的参数化派生类型数组,测试代码及编译报错如下:

测试代码

program test

  implicit none
  integer :: n_x, n_y, n_z

  type soils_type(n)
    integer, len :: n
    real, dimension(n) :: var1
  end type

  type cell_type(n)
    integer, len :: n
    type(soils_type(n)) :: soils
  end type

  type model_type
    type(cell_type(:)), allocatable :: modelgrid(:,:)
  end type

  type(model_type) :: m
  n_x = 2
  n_y = 3
  n_z = 3
  allocate(cell_type(n_z) :: m%modelgrid(n_x,n_y))

end program

编译错误

  • 使用gfortran 13.1.0编译时:
25 |   allocate(cell_type(n_z) :: m%modelgrid(n_x,n_y))
     |                             1
Error: Type of entity at (1) is type incompatible with typespec' 
  • 使用gfortran 11.2.0编译时:
main.f95:25:29:

   25 |   allocate(cell_type(n_z) :: m%modelgrid(n_x,n_y))
      |                             1
Error: Type of entity at (1) is type incompatible with typespec

[Compilation failed with exit code 1]

解决方案

错误原因

modelgrid的定义是type(cell_type(:)), allocatable :: modelgrid(:,:),这是一个二维可分配数组,数组的每个元素是cell_type(:)类型的可分配对象(延迟参数化类型),而非直接的参数化类型数组。原代码试图一次性分配外层数组和内层参数化实例,导致类型不匹配。

修正代码

需要分两步分配:先创建外层二维数组的结构,再逐个初始化每个元素为指定参数的参数化类型实例:

program test

  implicit none
  integer :: n_x, n_y, n_z, i, j

  type soils_type(n)
    integer, len :: n
    real, dimension(n) :: var1
  end type

  type cell_type(n)
    integer, len :: n
    type(soils_type(n)) :: soils
  end type

  type model_type
    type(cell_type(:)), allocatable :: modelgrid(:,:)
  end type

  type(model_type) :: m
  n_x = 2
  n_y = 3
  n_z = 3

  ! 第一步:分配外层二维数组,每个元素为未初始化的cell_type(:)
  allocate(m%modelgrid(n_x, n_y))

  ! 第二步:逐个将数组元素分配为cell_type(n_z)实例
  do j = 1, n_y
    do i = 1, n_x
      allocate(cell_type(n_z) :: m%modelgrid(i,j))
      ! 可选:初始化成员变量
      m%modelgrid(i,j)%soils%var1 = 0.0
    end do
  end do

  ! 验证分配结果
  print *, "modelgrid的维度:", shape(m%modelgrid)
  print *, "第一个cell的soils%var1长度:", size(m%modelgrid(1,1)%soils%var1)

end program

关键说明

  • 外层数组分配仅确定二维结构,每个元素此时是未分配的延迟参数化对象;
  • 通过循环逐个分配每个元素,明确指定参数n_z,确保类型匹配;
  • 若所有元素需使用相同参数,也可考虑将参数提升到model_type层级,但当前结构下必须分两步处理。

内容的提问来源于stack exchange,提问作者gcolumbus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:03:39