I have a Fortran program with an allocatable array A
as follows:
real, dimension(:,:) allocatable :: A
...
allocate(A(x0:x1;y0:y1))
This array is eventually passed as argument to a subroutine which looks like
subroutine my_subroutine(arr)
real, dimension(x0:x1,y0:y1) :: arr
...
end subroutine my_subroutine
I wanted to replace the allocate
statement of Fortran by a custom memory allocation function my_alloc
implemented in a C library. I changed the first code sample into:
type(c_ptr) :: cptr
real, pointer, dimension(:,:) :: A
...
cptr = my_alloc(...)
call c_f_pointer(cptr,A,[x1-x0+1,y1-y0+1])
This works fine, except that by specifying extents instead of lower/upper bounds in the c_f_pointer
function, I lose the original shape (x0:x1,y0:y1) of the array. But this is not a big problem: the pointer is passed as argument of the subroutine, the subroutine expects an array and considers the pointer as an array, with the proper bounds.
My real problem is: when I want to also rewrite the subroutine's code to have a pointer instead of an array.
subroutine my_subroutine(arr)
real, pointer, dimension(x0:x1,y0:y1) :: arr
...
end subroutine my_subroutine
The code above doesn't work; gfortran says
Array pointer 'arr' at (1) must have a deferred shape
The following code can be compiled
subroutine my_subroutine(arr)
real, pointer, dimension(:,:) :: arr
...
end subroutine my_subroutine
but it doesn't provide the bounds and the program crashes when I try to perform a loop from x0 to x1 and from y0 to y1.
How can I handle this case? Within the subroutine, I need fortran to know that arr
is a pointer to an array shaped (x0:x1,y0;y1).