Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating arrays in a Fortran Subroutine

I need to read a lot of data from a file in a Fortran program. The size of the data is variable, so I would like to dynamically allocate the arrays. My idea is to make a subroutine who reads all the data and allocates the memory. A simplified version of the program is:

  program main

  implicit none
  real*8, dimension(:,:), allocatable :: v
  integer*4 n

  !This subroutine will read all the data and allocate the memory 
  call Memory(v,n)

  !From here the program will have other subroutines to make calculations

  end


  subroutine Memory(v,n)

  implicit none
  real*8, dimension(:,:), allocatable :: v
  integer*4 n,i

  n=5
  allocate(v(n,2))
  do i=1,n
  v(i,1)=1.0
  v(i,2)=2.0 
  enddo

  return
  end subroutine Memory

This program gives me the following error:

Error: Dummy argument 'v' of procedure 'memory' at (1) has an attribute that requieres an explicit interface for this procedure

Is this the right way of structuring this kind of program? If so, How can I solve the error?

Thanks.

like image 892
Msegade Avatar asked Jan 12 '23 18:01

Msegade


1 Answers

Assuming that you have a single source file containing both the program and the subroutine, as your post suggests, the easiest fix is to replace the line containing the statement

end

with a line containing the statement

contains

and writing, at the end of the source file a line containing the statement

end program

(Yes, the keyword program is not required but it is useful.)

The problem that your compiler has reported is that, as you have structured your code, the program does not know anything about the interface to the subroutine memory, that interface is, in Fortran terms, implicit. When you want to call a subroutine and either pass in or pass out an allocatable array that subroutine must have an explicit interface.

There are several ways to provide an explicit interface. One is, as I have shown you, to contain the subroutine within the program. Another, and more useful way when your programs become a little bit larger, is to write your subroutines in modules and use-associate them in the program that wants to use them. Read the parts of your Fortran tutorial that cover modules and the use statement.

There is at least one other option but it is, especially for a beginner, unattractive and I won't mention it here.

And, while I'm writing, learn about and use the keyword intent to specify whether an argument to a subroutine will be read, written to or both. This is a great aid to safe programming, your favourite Fortran resources will explain in detail.

like image 119
High Performance Mark Avatar answered Mar 27 '23 17:03

High Performance Mark