title: Can I pass an array of arbitrary rank to a subroutine in Fortran?
body: <p>I'm writing a general output for a numerical model I've written. I produce arrays that are either 1,2,3 or 4 dimensions on unknown length. I'm running into issues in how to define the array in the subroutine (found in a different module). </p>
  
  <pre><code>gfortran -g -O0 -I/usr/include -c analysis.f90
  analysis.f90:136:32:
   call write_netcdf('domain', domain, 'binary_cloud_domain', 0)
                              1
  Error: Rank mismatch in argument ‘data_out’ at (1) (scalar and rank-4)
  </code></pre>
  
  <p>The error comes from this subroutine:</p>
  
  <pre><code>  subroutine binary_cloud_analysis
  
  use cloud, only: cloud_domain, cloud_smooth_domain
  use write, only: write_netcdf
  
  real, allocatable, dimension(:,:,:,:) :: domain, smth_domain
  
  allocate(domain(x_dim,y_dim,z_dim,t_dim), smth_domain(x_dim,y_dim,z_dim,t_dim))
  
  call cloud_domain(domain)
  
  if (cloud_smooth) then
    call cloud_smooth_domain(domain,smth_domain)
    domain = smth_domain
  endif
  
  call write_netcdf('domain', domain, 'binary_cloud_domain', 0)
  
  end subroutine binary_cloud_analysis
  </code></pre>
  
  <p>At the moment in the subroutine write_netcdf I've assigned data_out as </p>
  
  <pre><code>  subroutine write_netcdf(var_name, data_out, output_name, output_type)
  
  !--------------------------------------------------------------------------!
  ! input variables                                                          !
  !--------------------------------------------------------------------------!
  
  real(kreal), allocatable, intent (in) :: data_out
  </code></pre>
  
  <p>Understandably the compiler is taking this as a scalar as I haven't included a dimensions(:) type specifier because I don't know what type of array I'm passing in generality and I'd hoped it might be able to massage the dimensions due to the variable being allocatable. The output_type variable specifies what type of array we have i.e. 3d, 4d etc to help define the NetCDF file.</p>
  
  <p>I think I would be able to do it by reshaping the array into a 1d array and then reshaping back based on defining the number of dimensions and passing the lengths but ideally I wouldn't have these additional steps. Is there a way the define an allocatable array in sufficient generality for these purposes?</p>