Fortran中如何分配与已有多维数组同形但不同值的数组?
Fortran:按已有数组形状分配并初始化新数组的标准方法
问题场景
现有代码:
real(pReal), dimension(:,:,:), allocatable :: & first_array, & second_array first_array = custom_array_generating_function()
需要为second_array分配与first_array完全相同的形状,同时直接初始化为0_pReal,避免先通过mold分配再手动赋值的冗余操作(如下写法虽可行但不够高效):
allocate(second_array, mold=first_array) second_array = 0_pReal
尝试以下写法均因语法错误失败:
allocate(second_array(shape(first_array),source=0_pReal) allocate(second_array(size(first_array(1)),size(first_array(2)),size(first_array(3))),source=0_pReal) allocate(second_array(shape(first_array)(1),size(first_array)(2),size(first_array)(3)),source=0_pReal)
标准化解决方法
简洁写法(Fortran 2003+)
修正语法后,直接结合shape()函数和source参数即可实现需求:
allocate(second_array(shape(first_array)), source=0_pReal)
你之前的错误在于少了一个闭合括号,正确的语法是将shape(first_array)作为形状参数放在括号内,再通过source指定初始化值。这种写法是Fortran标准支持的,既保证形状匹配,又一步完成初始化,无需后续赋值。
兼容更早标准的写法
如果需要适配Fortran 95等更早版本,可以先提取形状再分配:
integer :: arr_dims(3) arr_dims = shape(first_array) allocate(second_array(arr_dims(1), arr_dims(2), arr_dims(3)), source=0_pReal)
内容的提问来源于stack exchange,提问作者Yes
相关产品推荐
相关产品推荐

