out*_*law 0 fortran gfortran fortran90
我想在 fortran90 中填充一个未知大小的数组。这是 MATLAB 中的等效代码:
for i=1:10
A[i] = i
end
Run Code Online (Sandbox Code Playgroud)
我知道我可以传递大小,但是如何在 fortran90 中执行此操作而不传递数组的大小。我读到我们可以使用指针,但我真的不知道如何处理指针
我知道您想在知道数组的最终大小之前开始向数组添加元素。
举个例子,您想要从文件中读取值,直到到达文件末尾,但不知道有多少个值。
我能想到的方法有以下三种:
创建一个足够大小的数组,并记住最终值。
integer :: a(200), n
n = 1
do
a(n) = <value>
if (<finished>) exit
n = n + 1
end do
<use a(1:n)>
Run Code Online (Sandbox Code Playgroud)
创建两个可分配数组,当到达一个数组的末尾时,使另一个更大,然后交换它们:
integer, allocatable :: a(:), tmp(:)
integer :: i, n
n = 8
allocate(a(n))
i = 1
do
if (i > n) then
allocate(tmp(2*n))
tmp(1:n) = a(:)
call move_alloc(tmp, a)
n = n * 2
end if
a(i) = <value>
if (<finished>) exit
i = i + 1
end do
allocate(tmp(i))
tmp(:) = a(1:i)
call move_alloc(tmp, a)
Run Code Online (Sandbox Code Playgroud)
我不再推荐这个了。指针可能会造成混乱并产生奇怪且难以调试的错误。但我把它留给后人:创建一个链接列表(这里使用堆栈)
type t_node
integer :: value
type(t_node), pointer :: next => NULL()
end type t_node
type(t_node), pointer :: list, tmp
integer, allocatable :: a(:), i, n
nullify(list)
nullify(tmp)
do
allocate(tmp)
tmp % value = <value>
tmp % next => list
list => tmp
nullify(tmp)
if (<finished>) exit
n = n + 1
end do
allocate(a(n))
do i = n, 1, -1
a(i) = list % value
tmp => list
list => list % next
deallocate(tmp)
end do
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6408 次 |
| 最近记录: |