I would like to create an array of pointers to arrays, which are dynamically allocated if/when my result is ready. The following code uses a type to get around being unable to set an array of pointers, but the function makeArray is always returning the same memory address.
The expected outcome would be different addressess, and thus separately controllable arrays. (I need to do this because I have very very large arrays that will be populated at random but must be ordered, and I don't want to preallocate a massive 2x2 array (order of 8GB) nor constantly reallocate and sort as new results come in, so my solution is preallocate a large 1x1 array that can have pointers to the 2nd dim, meaning I can place the pointer to the result in its correct "slot" if/when it becomes available)
module mymodule
contains
function makeArray(size)
integer :: size
integer, target, allocatable :: a(:)
integer, pointer :: makeArray(:)
allocate(a(size))
a = 0
makeArray => a
end function
end module mymodule
program test
use mymodule
implicit none
type :: IntPointer
integer, pointer :: ptr(:)
integer :: id
end type
type(IntPointer), allocatable :: ptrarray(:)
integer :: i
allocate(ptrarray(5))
ptrarray(1)%ptr => makeArray(1277)
ptrarray(1)%id = 1
ptrarray(2)%ptr => makeArray(13567)
ptrarray(2)%id = 2
ptrarray(1)%ptr(12) = 10
do i=1, size(ptrarray)
write(*,*) ptrarray(i)%id
write(*,*) LOC(ptrarray(i)%ptr)
end do
end program
Thanks
EDIT Solved, I'll keep this here for posterity: I suppose the crux of the issue is being able to allocate a 2d array where the 2nd dimension can vary significantly. The magic word I needed to look for was "Ragged Array" and it seems this post answers my question.