Re: can an allocatable array be really dynamic?
- From: Brooks Moses <bmoses-nospam@xxxxxxxxxxxxxxxxxx>
- Date: Sun, 06 Aug 2006 10:53:30 -0700
zhngbn@xxxxxxxxxxxxxxxx wrote:
If i have no idea of the exact amount of data that will be used, can i
still use the allocatable array? In other words, can the allocatable
array work like a linklist to allocate a node when needed? I donot want
to build a linklist because it is really time consuming when I try to
randomly use the data.Thank you!
The Fortran 2003 standard includes an intrinsic which allows for adding to an existing allocatable array without erasing the existing data. This isn't currently implemented in any compilers (which are still all Fortran 95 these days), but it's not that hard to do yourself in a slightly less efficient manner, with something like the following.
type expandable_array
real, pointer :: data(:)
integer :: ubound
integer :: data_ubound
end type
subroutine allocate_expandable(a, u)
type(expandable_array) :: a
integer :: u
a%ubound = u
a%data_ubound = u + 10
allocate(a%data(a%data_ubound))
end subroutine
subroutine reallocate_expandable(a, u)
type(expandable_array) :: a
real, pointer :: temp_data(:)
integer :: u
if u > a%data_ubound
a%data_ubound = a%data_ubound + 10
allocate(temp(1:a%data_ubound))
temp(1:a%ubound) = a(1:a%ubound)
deallocate(a%data)
a%data => temp
end if
a%ubound = u
end subroutine
That's unfinished in a number of ways; most notably, the choice of a new value for a%data_ubound is exceptionally poor -- it should be guaranteed to be larger than u, for one thing, and 10 may not be the most efficient number to use -- you want to pick something that balances the extra wasted memory against the number of times you have to reallocate. Also, since a%data is a pointer rather than an allocatable, you probably also want a deallocate_expandable subroutine.
- Brooks
--
The "bmoses-nospam" address is valid; no unmunging needed.
.
- Follow-Ups:
- Re: can an allocatable array be really dynamic?
- From: zhngbn
- Re: can an allocatable array be really dynamic?
- References:
- can an allocatable array be really dynamic?
- From: zhngbn
- can an allocatable array be really dynamic?
- Prev by Date: Re: can an allocatable array be really dynamic?
- Next by Date: Re: 2+2=4, but only once !?
- Previous by thread: Re: can an allocatable array be really dynamic?
- Next by thread: Re: can an allocatable array be really dynamic?
- Index(es):
Relevant Pages
|