在 Fortran 中仅为二维数组分配一维

Allocate only one dimension for a 2D array in fortran

假设我有一个二维数组 A(:,2),其中只有第一维的大小未知。 是否可以只分配 A 的第一个维度? 如果不是,我每次都必须将 A 视为 A(:,:)。

如果第二维的大小始终为 2,您可以创建具有两个变量的数据类型,然后分配它们的数组:

program main
    implicit none

    type two_things
        integer :: first
        integer :: second
    end type two_things

    type(two_things), dimension(:), allocatable :: A

    allocate(A(100))

    A(1)%first = 1
    A(1)%second = 2

    print*, A(1)%first, A(1)%second, shape(A)

    deallocate(A)

end program main