title: Fortran array of variable size arrays
body: <p>A simplified description of the problem:</p>
  
  <p>There are exactly <em>maxSize</em> people shopping in a store. Each of them has a shopping list, containing the price of items (as integers). Using Fortran arrays, how can I represent all the shopping lists. The shopping lists may contain <em>any</em> number of items (1, 10, 1000000000).</p>
  
  <p>(NOTE: The actual problem is far more complicated. It is not even about shopping.)</p>
  
  <p>The lazy approach would be:</p>
  
  <pre><code>integer :: array(maxSize, A_REALLY_BIG_NUMBER)
  </code></pre>
  
  <p>However, this is very wasteful, I basically want the second dimension to be variable, and then allocate it for each person seperately.</p>
  
  <p>The obvious attempt, doomed to failure:</p>
  
  <pre><code>integer, allocatable :: array(:,:)
  allocate(array(maxSize, :)) ! Compiler error
  </code></pre>
  
  <p>Fortran seems to require that arrays have a fixed size in each dimension.</p>
  
  <p>This is wierd, since most languages treat a multidimensional array as an "array of arrays", so you can set the size of each array in the "array of arrays" seperately.</p>
  
  <p>Here is something that <em>does</em> work:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>If this is the only solution, I guess I will use it. But I was kind of hoping there would be a way to do this using intrinsic functions. Having to define a custom type for such a simple thing is a bit annoying.</p>
  
  <p>In C, since an array is basically a pointer with fancy syntax, you can do this with an array of pointers:</p>
  
  <pre><code>int sizeAt(int x); //Function that gets the size in the 2nd dimension
  int * array[maxSize];
  
  for (int x = 0; x &lt; maxSize; ++x)
          array[x] = (int*)(calloc(sizeAt(x) , sizeof(int)));
  </code></pre>
  
  <p>Fortran seems to have pointers too. But the only tutorials I have found all say "NEVER USE THESE EVER" or something similar.</p>