Re: Allocating arrays inside a subroutine.
- From: Timothy Hume <T.Hume@xxxxxxxxxx>
- Date: Wed, 30 Aug 2006 09:27:23 +1000
Thanks to everyone who suggested solutions to my problem. I am now able to
make progress on my code again. I was also unaware of the CHARACTER(LEN=*)
feature ... this will also make my life easier.
Thanks,
Tim Hume
Bureau of Meteorology Research Centre
Melbourne
Australia
On 30/8/06 4:50 AM, in article 44F48C6A.7530B09A@xxxxxxxxxxxxx, "Walter
Spector" <w6ws_xthisoutx@xxxxxxxxxxxxx> wrote:
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
.
- References:
- Allocating arrays inside a subroutine.
- From: Timothy Hume
- Re: Allocating arrays inside a subroutine.
- From: Walter Spector
- Allocating arrays inside a subroutine.
- Prev by Date: Re: How to USE modules in a different directory?
- Next by Date: Re: closing unit=5 and unit=6 and print *
- Previous by thread: Re: Allocating arrays inside a subroutine.
- Next by thread: Is there any good nemerical methods to do Indefinite Integrals with fortran?
- Index(es):
Relevant Pages
|