为什么我们不能通过变量定义数组大小?

Why can't we define the array size by a variable?

我发现数组大小可以通过参数来定义,但不能通过变量来定义。下面给出一个例子来解释我在说什么。

第一个示例 - 不工作:

integer :: narr=100
integer, dimension(narr) :: Total

第二个示例 - 工作:

integer, parameter :: narr=100
integer, dimension(narr) :: Total

在第一个示例中,我希望 dimension 可以使用变量 narr,因为首先定义了 narr。但我意识到这可能不是真的,因为变量的创建可能不遵循我的代码行的顺序。也许只有Python出身的人才会这么想。

在第二个示例中,一切正常。

我推测差异与创建变量和常量的时间有关。谁能解释一下其中的奥秘?

在您的示例中,由于 integer, dimension(narr) :: Total 没有 allocatablepointer 属性,它是静态数组或自动数组,具体取决于上下文(我' m 省略了假设的形状数组,因为这个问题具体是关于 defining 数组)。在任何一种情况下,它的大小都必须是一个编译时常量或一个伪参数。在第一个示例中,narr 两者都不是,这使得它在 Fortran 中无效。为了使用 narr 作为非常量变量来指定大小,您需要通过包含 allocatablepointer 属性将 Total 声明为动态数组。根据具体情况,这可能会降低性能,但它可以更灵活地定义数组绑定的方式和位置。

以下是在 Fortran 中定义静态和动态数组的一些常用方法:

  ! Static
  call test_fixed_size()
  call test_size_parameter()

  ! Dynamic
  call test_allocatable()
  call test_pointer()
  call test_automatic(10)

contains
  subroutine test_fixed_size()
    integer :: array(10)
    array = 1
  end subroutine test_fixed_size

  subroutine test_size_parameter()
    integer, parameter :: size = 10
    integer :: array(size)
    array = 1
  end subroutine test_size_parameter

  subroutine test_allocatable()
    integer, allocatable :: array(:)
    integer :: narr = 100
    allocate(array(narr))
    array = 1
  end subroutine test_allocatable

  subroutine test_pointer()
    integer, pointer :: array(:) => null()
    integer :: narr = 100
    allocate(array(narr))
    array = 1
    deallocate(array)
  end subroutine test_pointer

  subroutine test_automatic(size)
    integer, intent(in) :: size
    integer :: array(size)
    array = 1
  end subroutine test_automatic
end program

(我在这里省略了更现代的功能,例如分配时的自动分配。)