next up previous contents
Next: Status of a Pointer Up: Association with Arrays Previous: Association with Arrays   Contents

Example: Array swapping

This example shows the usufulness of pointers. Suppose we want to swap 2 large arrays. The direct code will involve creating an extra array and copying a large amount of data 3 times:
real, dimension(1000,1000):: A, B, Tmp  
Tmp=A; A=B; B=Tmp  ! 3 array copies involved
If we decide to work with pointers to arrays in the code swapping will only involve changing pointer values, which is considerably more efficient:
real, dimension(1000,1000) :: mat1, mat2  
real, dimension(:,:), pointer :: a, b, tmp  
a=>mat1; b=> mat2        ! initial
tmp=>a; ! tmp points to the target of  a,  i.e. to mat1
a=>b;   !  a  points to the target of  b,  i.e. to mat2
b=>tmp  !  b  points to the target of tmp, i.e. to mat1
or even better:
real, dimension(1000,1000), target :: MatA, MatB  
real, dimension(:,:), pointer :: A, A  
A=>MatA; B=>MatB   ! normal  
A=>MatB; B=>MatA   ! swapped

Adrian Sandu 2001-08-26