title: How to get priorly-unknown array as the output of a function in Fortran
body: <p>In <strong>Python</strong>:  </p>
  
  <pre><code>def select(x):
      y = []
      for e in x:
          if e!=0:
              y.append(e)
      return y
  </code></pre>
  
  <p>that works as:</p>
  
  <pre>
  x = [1,0,2,0,0,3]
  select(x)
  [1,2,3]
  </pre>
  
  <p>to be translated into <strong>Fortran</strong>:</p>
  
  <pre class="lang-fortran prettyprint-override"><code>function select(x,n) result(y)
      implicit none
      integer:: x(n),n,i,j,y(?)
      j = 0
      do i=1,n
          if (x(i)/=0) then
              j = j+1
              y(j) = x(i)
          endif
      enddo
  end function
  </code></pre>
  
  <p>The questions are in Fortran:</p>
  
  <ol>
  <li><strong>how to declare y(?)</strong>?  </li>
  <li><strong>how to declare predefined values for x</strong>  </li>
  <li><strong>how to avoid dimension info n</strong>  </li>
  </ol>
  
  <p>for 1 if it is defined as <strong>y(n)</strong> the output will be:</p>
  
  <pre>
  x = (/1,0,2,0,0,3/)
  print *,select(x,6)
  1,2,3,0,0,0
  </pre>
  
  <p>which is not desired!<br>
  !-------------------------------<br>
  <strong>Comments:</strong><br>
  <strong>1-</strong> All given answers are useful in this post. Specially M.S.B and eryksun's.<br>
  <strong>2-</strong> I tried to adapt the ideas for my problem and compile with <code>F2Py</code> however it was not successful. I had already debugged them using GFortran and all were successful. It might be a bug in <code>F2Py</code> or something that I don't know about using it properly. I will try to cover this issue in another post.</p>
  
  <p><strong>Update:</strong>
  A linked question could be found at <a href="https://stackoverflow.com/questions/8487043/f2py-working-with-allocatable-arrays-in-fortran-being-invoked-through-python">here</a>.</p>