0

I want to store a 3D array pointer into a 4D array pointer but I am having some trouble. For example:

real,pointer :: p(:,:,:,:) => null()
integer :: ndims,d

ndims = 3
do d=1,ndims
  p(d,:,:,:) => function
end do

Where function is a function pointer which returns a pointer such as p(:,:,:) and this works fine. The error I am getting is that Lower bound has to be present at this line: p(d,:,:,:) => function, but I have performed this sort of operations before (not with pointers) and it worked okay. What am I missing here?

b-fg
  • 3,959
  • 2
  • 28
  • 44
  • You currently have a single rank four pointer. At any one time, you can *point* that single rank four pointer at a single target array. Perhaps http://stackoverflow.com/a/8901228/1234550 might help. – IanH Jul 20 '16 at 12:51
  • Yes, but I want to point at at different rank 3 arrays and store this in the rank 4 pointer, where the extra rank account for these different arrays. Is this actually possible? – b-fg Jul 20 '16 at 13:03

1 Answers1

3

I think this comes from a common misunderstanding of what

real,pointer :: p(:,:,:,:) => null() 

is actually doing in fortran.

It is not a 4D array of pointers but a pointer 'p' to a 4D array.

What you can do is play a little trick and create a struct with a pointer inside:

type pointer4D
   real, pointer :: p
end type pointer4D
type(pointer4D), dimension(:) :: arr

Your code would thus become:

do d=1,ndims
  arr(d)%p => function
end do

Assuming 'function' is some sort of 3D object, you can access the element I,j,k of the dimension N by doing

arr(N)%p(I,j,k)
Scarlehoff
  • 89
  • 3
  • Ok, this makes sense. Yeap, I was basically confused by the definition of `p`. This is different as in c++ right? – b-fg Jul 20 '16 at 14:46
  • @bfg yes. In C++, if I'm not mistaken, you can define an array of pointers as p[ndim]. This is not possible in Fortran. – Scarlehoff Jul 20 '16 at 14:53