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

pointer problem

Li_Dong
Beginner
897 Views
Hi all,

I need a pointer array that is pointed to elements of an array like this:
[fortran]integer, target :: a(5)
integer, pointer :: b(:)[/fortran]
array a(5): 1 2 3 4 5
pointer b(2): ^ ^
That is, "b" can point to any two element of "a". Does Fortran have this feature?
Cheers,
DONG Li
0 Kudos
3 Replies
Tim_Gallagher
New Contributor II
897 Views
You could give it the start location, end location, and stride to have the effect you are looking for.

For example:

[fortran]PROGRAM ptr
   IMPLICIT NONE

   INTEGER, DIMENSION(5), TARGET :: a
   INTEGER, DIMENSION(:), POINTER :: b

   a = (/ 1, 2, 3, 4, 5 /)
   b => a(2:5:3)

   PRINT *, b
END PROGRAM ptr
[/fortran]

The range you point to could be run-time defined as a(start:end:(end-start)) which would work for all cases except when start = end, in that case the stride needs to be 1 (which mean b is an array of dimension 1).

Tim
0 Kudos
Li_Dong
Beginner
897 Views
Thanks Tim. Is there more elegant way to accomplish this? If I need to point more than two elements, what should I do?
0 Kudos
reinhold-bader
New Contributor II
897 Views
Hello,

As far as elegance is concerned: it is hard to imagine how Tim's solution can be improved.

If you need to point to a subset of elements, there appear to be two cases:
Case 1: The subset is an array slice i.e. a regular sublattice inside the original array.
In this case Tim's solution simply generalizes since you can say
b => a(start:end:stride)
Case 2: The subset is not an array slice, but requires an index vector, say
iv = (/ i1, i2, i3, ...., in /)
to describe it. The usual way for dealing with this situation is to use iv as a vector subscript,
or iterate through elements of iv: c(i) = a(iv(i)). If you insist that pointers are required, you would
need to introduce a derived type, say
type :: irregular
real, pointer :: p
end type

and use an array entity of that type:

type(irregular) :: b(3)
b(1)%p => a(iv(1)); b(2)%p => a(iv(2)); b(3)%p => a(iv(3))

Regards
Reinhold
0 Kudos
Reply