gpt4 book ai didi

Fortran 数组元素在内存中的顺序

转载 作者:行者123 更新时间:2023-12-05 03:23:55 24 4
gpt4 key购买 nike

我用的是在线IDE,貌似都不支持调试。如果我有一个像下面这样的 4D 数组?如何按照元素在内存中的顺序打印数组的所有元素?

Program Hello
integer :: test(2,3,4,5), i1,i2,i3,i4, val;
val = 0

do i1=1,2
do i2=1,3
do i3=1,4
do i4=1,5
test(i1, i2, i3, i4) = val
val = val +1
end do
end do
end do
end do

End Program Hello

最佳答案

fortran 中的数组/矩阵内存是按顺序排列的,即内存中的连续元素是数组中最左边维度的元素。

您只需发送整个数组的 printwrite 命令即可打印整个数组。

在这个例子中,首先我们用增量索引填充一维数组;然后,将它们重新整形为 4 维数组,这样您就可以看到 4 维数组项如何首先递增最左边的维度:

program test_print
use iso_fortran_env, only: output_unit
implicit none

integer :: test(2,3,4,5), global_index(2*3*4*5)
integer :: i,j,k,l

! Fill 1D array with incremental values
forall(i=1:size(global_index)) global_index(i) = i

! Reshape 1D array to 4D
test = reshape(global_index,[2,3,4,5])

! Print whole array to screen
! Should print 1 2 3 4 5 6 7......
print "(*(1x,i0))", test

! This is same as:
write(output_unit,"(*(1x,i0))") test

end program test_print

关于Fortran 数组元素在内存中的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72420840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com