5

私はFortranコードを使用していますが、少し戸惑っています。

サブルーチンがあります、例えば

SUBROUTINE SSUB(X,...)
REAL*8 X(0:N1,1:N2,0:N3-1),...
...
RETURN 
END

これは、別のサブルーチンで次のように呼び出されます。

CALL SSUB(W(0,1,0,1),...)

ここで、Wは「作業配列」です。Wからの特定の値がXに渡されているように見えますが、Xは配列として次元化されています。どうしたの?

4

3 に答える 3

9

これは、サブルーチンを元の配列の(N次元の長方形)サブセットで機能させるための珍しいイディオムではありません。

Fortranのすべてのパラメーター(少なくともFortran 90より前)は参照によって渡されるため、実際の配列引数はメモリー内の場所として解決されます。配列全体に割り当てられたスペース内の場所を選択すると、サブルーチンは配列の一部のみを操作します。

最大の問題:配列がメモリ内にどのように配置されているか、Fortranの配列索引付けスキームがどのように機能するかを知っておく必要があります。Fortranは、cとは逆の規則である列の主要な配列の順序を使用します。サイズが5x5の配列を考えてみましょう(cとの比較を容易にするために、0から両方向にインデックスを付けます)。どちらの言語でも、0,0はメモリの最初の要素です。cでは、メモリ内の次の要素はです[0][1]が、Fortranではです(1,0)。これは、部分空間を選択するときにドロップするインデックスに影響します。元の配列がA(i、j、k、l)であり、サブルーチンが3次元部分空間で機能する場合(例のように)、cでは機能しますAprime[i=constant][j][k][l]がFortranで動作しAprime(i,j,k,l=constant)ます。

The other risk is wrap around. The dimensions of the (sub)array in the subroutine have to match those in the calling routine, or strange, strange things will happen (think about it). So if A is declared of size (0:4,0:5,0:6,0:7), and we call with element A(0,1,0,1), the receiving routine is free to start the index of each dimension where ever it likes, but must make the sizes (4,5,6) or else; but that means that the last element in the j direction actually wraps around! The thing to do about this is not use the last element. Making sure that that happens is the programmers job, and is a pain in the butt. Take care. Lots of care.

于 2010-03-22T18:57:36.050 に答える
3

This is called "sequence association". In this case, what appears to be a scaler, an element of an array (actual argument in caller) is associated with an array (implicitly the first element), the dummy argument in the subroutine . Thereafter the elements of the arrays are associated by storage order, known as "sequence". This was done in Fortran 77 and earlier for various reasons, here apparently for a workspace array -- perhaps the programmer was doing their own memory management. This is retained in Fortran >=90 for backwards compatibility, but IMO, doesn't belong in new code.

于 2010-03-23T02:17:25.880 に答える
2

fortranでは、変数はアドレスによって渡されます。W(0,1,0,1)価値と住所もそうです。したがって、基本的には、で始まるサブ配列を渡しますW(0,1,0,1)

于 2010-03-22T18:49:28.593 に答える