如何在Fortran中将1-D数组指针指向可分配的2-D数组

时间:2018-01-15 22:27:43

标签: fortran

我想引用一个二维数组,其大小在运行时确定,作为一维数组而不复制或改变原始数组。由于Fortran使用指针指向数组而不是指针数组,因此直接使用指针在我尝试过的任何排列中都不起作用。 EQUIVALENCE似乎只适用于常量大小的数组,TRANSFER返回一个副本。 1-D数组的特定顺序并不重要(即[x11,x12,x13...][x11,x21,x31...]一样好,但是当我改变2-D数组时,我希望看到1-中反映出的变化D阵列,反之亦然。

理想情况下,我可以做类似的事情:

program arr_as_vec

    implicit none
    real, allocatable, target :: arr(:,:)
    real, pointer :: vec(:)
    integer :: dim1, dim2 ! would really be determined at runtime

    dim1 = 3; dim2 = 5
    allocate(arr(dim1,dim2))
    call something_like_equivalence(arr, vec)

    arr(1,1) = 1
    arr(dim1,dim2) = 2
    print *, vec(1) ! should give 1
    print *, vec(dim1*dim2) ! should give 2

end program arr_as_vec

这可能吗?

1 个答案:

答案 0 :(得分:0)

使用指针重新映射,以下工作与gfortran 5.4.0一样正常(由于francescalus,roygvib和VladamirF的帮助而编辑):

program arr_as_vec

    implicit none
    real, allocatable, target :: arr(:,:)
    real, pointer :: vec(:)
    integer :: dim1, dim2 ! would really be determined at runtime

    dim1 = 3; dim2 = 5
    allocate(arr(dim1,dim2))
    vec(1:dim1*dim2) => arr

    arr(1,1) = 1
    arr(dim1,dim2) = 2
    print *, vec(1) ! should give 1
    print *, vec(dim1*dim2) ! should give 2
    print *, size(vec) ! should give 15
    vec(1) = 3
    print *, arr(1,1) ! should be 3

end program arr_as_vec