title: Fortran increase dynamic array size in function
body: <p>I need a variable size array in Fortran. In C++ I would use vector. So I have a function like </p>
  
  <pre><code>integer function append(n, array, value)
    integer, pointer, dimension(:) :: array
    integer, pointer, dimension(:) :: tmp_arr
    integer n
  
    if (size(array) .eq. n) then
       allocate(tmp_arr(2*size(array)))
       tmp_arr(1:size(array)) = array
       deallocate(array)
       array =&gt; tmp_arr
    end if
    n = n + 1
    array(n) = value
    append = n
  end function
  </code></pre>
  
  <p>that works fine if I use it the way</p>
  
  <pre><code>integer pos, val
  pos = append(n, array, val)
  </code></pre>
  
  <p>However, if I would like to use it the way</p>
  
  <pre><code>integer i,j,n ! i,j&lt;n
  array(i) = append(n, array, array(j))
  </code></pre>
  
  <p>with gfortran this does not work. It compiles, but segfaults. The problem seems to be that gfortran makes addresses out of array(i) and array(j), sends the latter to the function append, and then when the address of array(j) is accessed and the one of array(i) written, the address space has been deallocated.</p>
  
  <p>What I would like is that the value of array(j) is put on the stack (not the address) and then used in the function and after the function has finished the uptodate address of array(i) is looked up and the result of the function saved to it.</p>
  
  <p>I am pretty sure gcc would do it the way I want, why is gfortran so mean?</p>
  
  <p>Is there any way in Fortran to make a robust (meaning the array(j) = ... example works)
  function or data type to have a c++ stl vector like behaviour?</p>
  
  <p>Conclusion:</p>
  
  <p>I eventually introduced temporary variables</p>
  
  <pre><code>integer tmp_val
  tmp_val = value
  ...
  array(n) = tmp_val
  </code></pre>
  
  <p>so at least the method can be called as </p>
  
  <pre><code>pos = append(n, array, array(j))
  array(i) = pos
  </code></pre>
  
  <p>and hope that other/future developers on the project won't try to 'optimize' the two lines to eliminate the necessity of 'pos'.</p>
  
  <p>Thanks for the answers and comments.</p>