I am trying to create an array of arrays in Fortran.
Something like the following
TYPE :: array_of_arrays
REAL, DIMENSION(:), POINTER :: p => NULL()
END TYPE
TYPE(array_of_arrays), DIMENSION(2) :: some_array
So that I can do:
REAL, DIMENSION(3), TARGET :: some_vector1 = (/1.0, 2.1, 4.3/)
REAL, DIMENSION(3), TARGET :: some_vector2 = (/3.0, 1.2, 9.6/)
some_array(1)%p => some_vector1
some_array(2)%p => some_vector2
WRITE(*,*) some_array(1)%p ! I see some_vector1
WRITE(*,*) some_array(2)%p ! I see some_vector2
Now it’s cumbersome for me to actually declare each of these some_vector arrays to correspond to each element in my array of arrays.
What I’d like to do is have in a separate subroutine where a temporary vector is set as a target, and that subroutine sets up my array of arrays to point to that temporary vector.
This way I can have anonymous arrays.
However, this doesn’t seem to be working and I wonder if first if I am doing something that Fortran doesn’t support.
So does Fortran support anonymous arrays, that is (in case I have the terms wrong), an array who can only be accessed through a reference?
Sure; as IanH suggests, you can just have the pointer refer to allocated memory directly, rather than refer to a variable; this is one of the few cases where the allocated memory doesn’t automatically get deallocated once it goes out of scope.
eg,
and running it gives