Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

(Re)Allocatable Arrays

Intel_C_Intel
Employee
216 Views
I've read many posts on this board to do with ALLOCATABLE arrays and doing things like replicating VB's ReDim Preserve by allocating a temporary array, copying the original, deallocating then reallocating the original and copying back again.
Now the clever people always suggest using a POINTER array to reduce the amount of copying required. Try as I might, and read and re-read those posts as I have, I just can't seem to grasp the concept behind these POINTER arrays.
Can anyone please explain it to me in thicko-moron-baby-steps? Preferably with a little example, detailing where things are stored and what points to what?
Thanks a lot.
0 Kudos
1 Reply
jim_dempsey
Beginner
216 Views
A "pointer array" would be an array of pointers. However, I do not believe that this is what you want to use to implement the VBreallocate preserve. I believe what you want to use is a single"pointer to and array". There are many ways to implement this. I will provide a simple, non-optimal, but easy to understand example:
real, pointer :: MyArray(:) => null()
real, target, allocatable :: hidden1MyArray(:)
real, target, allocatable :: hidden2MyArray(:)
! Allocate - first time
! sanity check
if(associated(MyArray)) stop 1
if(allocated(hidden1MyArray)) stop 2
if(allocated(hidden2MyArray)) stop 3
! allocate to hidden allocatable array
allocate(hidden1MyArray(1:Count), STAT=iStat)
if(iStat .ne. 0) stop 4
! point to array
MyArray => hidden1MyArray
...
! Reallocate
! sanity check
if(.not. associated(MyArray)) stop 4
! see which hidden array is current
if(allocated(hidden1MyArray)) then
! 1 is current, 2 must be void
if(allocated(hidden2MyArray)) stop 5
allocate(hidden2MyArray(1:NewCount), STAT=iStat)
if(iStat .ne. 0) stop 6
! make copy (truncate if new array shorter)
hidden2MyArray = hidden1MyArray
! null fill if new array larger
if(NewCount .gt. size(hidden1MyArray)) hidden2MyArray(size(hidden1MyArray)+1:) = 0.
! point to new array
MyArray => hidden2MyArray
! delete old array
deallocate(hidden1MyArray)
else
allocate(hidden1MyArray(1:NewCount), STAT=iStat)
if(iStat .ne. 0) stop 8
hidden1MyArray = hidden2MyArray
if(NewCount .gt. size(hidden2MyArray)) hidden1MyArray(size(hidden2MyArray)+1:) = 0.
MyArray => hidden1MyArray
deallocate(hidden2MyArray)
endif
Notes, the above error tests are not fool proof as MyArray might point to something other than either of the two hidden arrays. I will leave this up to you to fill in the error testing.
Jim Dempsey
0 Kudos
Reply