Re: Allocating arrays inside a subroutine.
- From: Walter Spector <w6ws_xthisoutx@xxxxxxxxxxxxx>
- Date: Tue, 29 Aug 2006 18:50:33 GMT
Timothy Hume wrote:
Hi,
I'm wondering if someone could point me in the right direction with this
problem. I'm a new Fortran 90/95 user, but am familiar with 77.
I want to create a Fortran 90 subroutine that reads data from a file, and
returns it in an array, which is one of the arguments to the subroutine...
[snip]
I'm sure this must be a common problem?
Yup. There are two ways.
1.) Use a POINTER argument for your data. This is standard Fortran-90:
subroutine read_data (filename, data_array)
character(*), intent(in) :: filename
real, pointer :: data_array(:)
:
read (unit) nrecords ! header record...
allocate (data_array(nrecords))
! read rest of file
end subroutine
Note that the interface to this subroutine must be explicit to the caller.
So it is recommended that it resides in a module that gets USEd by its caller.
Keep in mind that with POINTERs, memory leakage is a possibility.
2.) As others have noted, if your compiler supports the F2003 ALLOCATABLE array
capability, you can rewrite the above as:
subroutine read_data (filename, data_array)
character(*), intent(in) :: filename
real, allocatable :: data_array(:)
:
read (unit) nrecords ! header record...
allocate (data_array(nrecords))
! read rest of file
end subroutine
Again an explicit interface is required. But with ALLOCATABLE arrays one
does not have to worry about memory leakage.
Last, unrelated to your question, but...
SUBROUTINE READ_DATA(FILENAME, DATA_ARRAY)
CHARACTER(LEN=128), INTENT(IN) :: FILENAME
Note that the above is almost always a bug. That is, unless every one of your
file names is *exactly* 128 characters long. I suspect you meant CHARACTER(LEN=*)
instead.
HTH,
Walt
.
- Follow-Ups:
- Re: Allocating arrays inside a subroutine.
- From: Timothy Hume
- Re: Allocating arrays inside a subroutine.
- References:
- Allocating arrays inside a subroutine.
- From: Timothy Hume
- Allocating arrays inside a subroutine.
- Prev by Date: Re: How to USE modules in a different directory?
- Next by Date: Re: Merge sort in fortran 90 for linked lists
- Previous by thread: Re: Allocating arrays inside a subroutine.
- Next by thread: Re: Allocating arrays inside a subroutine.
- Index(es):
Relevant Pages
|