[英]Segmentation fault with array indexing in Fortran
Let A
and I
be an arrays of the integer type with dimension N. In general, I
is a permutation of the integers 1:N
. 设
A
和I
是具有维数N的整数类型的数组。通常, I
是整数1:N
的排列。 I want to do A(1:N) = A(I(1:N))
. 我想做
A(1:N) = A(I(1:N))
。 For small N
this works fine, but I got Segmentation fault
when N
is large. 对于小
N
这很好,但是当N
很大时我得到了Segmentation fault
。 Here is an example of what I actually did: 这是我实际做的一个例子:
integer N
integer,dimension(:),allocatable::A,I
N = 10000000
allocate(A(N))
allocate(I(N))
A = (/ (i,i=1,N) /)
I = (/ (N-i+1,i=1,N) /)
A(1:N) = A(I(1:N))
Is there a better way to do this? 有一个更好的方法吗?
It seems that A(I(1:N))
is valid syntax, at least in my testing ( gfortran 4.8
, ifort 16.0
, pgfortran 15.10
). 似乎
A(I(1:N))
是有效的语法,至少在我的测试中( gfortran 4.8
, ifort 16.0
, pgfortran 15.10
)。 One problem is that i
and I
are the same thing, and the array I
cannot be used in an implied do as you are doing. 一个问题是
i
和I
是同一个东西,并且I
不能像你一样在暗示中使用数组。 Replacing it with j
yields a program that runs for me: 用
j
替换它会产生一个为我运行的程序:
program main
implicit none
integer :: N, j
integer, allocatable, dimension(:) :: A, I
! -- Setup
N = 10000000
allocate(A(N),I(N))
A = (/ (j,j=1,N) /)
I = (/ (N-j+1,j=1,N) /)
! -- Main operation
A(1:N) = A(I(1:N))
write(*,*) 'A(1): ', A(1)
write(*,*) 'A(N): ', A(N)
end program main
As to why you're seeing a segmentation fault, I guess you're running out of memory when the array sizes get huge. 至于为什么你会看到一个分段错误,我猜你在阵列大小变大时就会耗尽内存。 If you're still having trouble, though, I suggest the following.
但是,如果你仍然遇到麻烦,我建议如下。
Instead of using A(1:N) = A(I(1:N))
, you really should be using a loop, such as 而不是使用
A(1:N) = A(I(1:N))
,你真的应该使用循环,例如
! -- Main operation
do j=1,N
Anew(j) = A(I(j))
enddo
A = Anew
This is more readable and easier to debug moving forward. 这样更易读,更容易调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.