问题简述:
商店里恰好有maxSize个人在购物。每个人都有一个购物清单,其中包含物品的价格(以整数表示)。如何使用Fortran数组表示所有购物清单。购物清单可能包含任意数量的物品(1、10、1000000000等)。
(注意:实际问题要复杂得多。它甚至与购物无关。)
懒惰的方法是:
integer :: array(maxSize, A_REALLY_BIG_NUMBER)
然而,这非常浪费,我基本上希望第二维是可变的,并且为每个人单独分配。
显然的尝试注定要失败:
integer, allocatable :: array(:,:)
allocate(array(maxSize, :)) ! Compiler error
Fortran似乎要求每个维度的数组都有固定的大小。
这很奇怪,因为大多数语言将多维数组视为"数组的数组",因此可以单独设置"数组的数组"中每个数组的大小。
下面是一些可行的方法:
type array1D
integer, allocatable :: elements(:) ! The compiler is fine with this!
endtype array1D
type(array1D) :: array2D(10)
integer :: i
do i=1, size(array2D)
allocate(array2D(i)%elements(sizeAt(i))
enddo
如果这是唯一的解决方案,我想我会使用它。但我有些希望能够使用内部函数来完成这个任务。为了实现如此简单的事情而定义一个自定义类型有点烦人。
在C语言中,由于数组基本上是具有花哨语法的指针,因此您可以使用指针数组来完成此操作:
int sizeAt(int x); //Function that gets the size in the 2nd dimension
int * array[maxSize];
for (int x = 0; x < maxSize; ++x)
array[x] = (int*)(calloc(sizeAt(x) , sizeof(int)));
Fortran似乎也有指针。但我找到的所有教程都说“永远不要使用这些”或类似的话。