我如何通过函数来增长这个数组?

问题描述 投票:0回答:1

作为一名 Fortran 菜鸟(抱歉……),我遇到了如何通过这样做来增长数组:

program grow_an_array
    implicit none
    integer ,dimension(:),allocatable :: num1,num2
    integer :: n


    allocate(num1(10))
    do n=1,50 !note that n goes beyond the bounds of array num1
        if(n>size(num1,dim=1))call growarray()
        num1(n)=n
    end do
    print *

contains

subroutine growarray()
    implicit none

    allocate(num2(size(num1,dim=1)+1))
    num2(1:size(num1))= num1(1:size(num1,dim=1))
    call move_alloc(num2,num1)


end subroutine

end program

两个数组都是全局的,所以一切正常,但我很想看到同样的事情的示例,但使用函数调用。

主要逻辑...

原始大小的数组称为 num1

调用growarray(num1)的函数

num1 现在是扩大后的数组,准备用于额外存储,而主逻辑并不知道。

我不知道你是否应该将指向 num1 的指针传递到函数中,并返回 num1 的新指针值并将其分配给 num1,或者其他......我仍在尝试学习传递数组一般来说,功能。

arrays fortran
1个回答
0
投票

您的方法没问题,并且可以用将数组作为参数的例程进行推广。重点是,在例程中,必须使用

allocatable
属性声明数组才能使其工作:

subroutine growarray(arr,newsize)
    implicit none
    integer, allocatable, intent(inout) :: arr(:)
    integer, intent(in) :: newsize

    integer, allocatable :: tmp(:)

    allocate( tmp(newsize) )
    tmp(1:size(arr))= arr(:)
    call move_alloc(tmp,arr)
end subroutine

请注意,正如评论中提到的,您不应该将 Fortran 数组视为经典指针,它们是特定的对象。

© www.soinside.com 2019 - 2024. All rights reserved.