Passing a subset of an array to a subroutine without creating a temporary array

Dear all,

I wonder if there is a way of passing a non-contiguous subset of a multi-dimensional array to a subroutine while avoiding the creation of a temporary copy of the array in runtime, and without changing the subroutine (e.g. for interfacing with an external library).

Thanks!

If the called subroutine expects an assumed shape (A(:,:)) dummy argument, or a pointer, or (less likely) an assumed-type or assumed-rank dummy argument, then there shouldn’t be a temporary unless the actual argument has a vector valued subscript or is the result of a function.

But if the called subroutine expects an explicit shape or assumed size dummy argument array, and the actual argument data are truly noncontiguous, then you are out of luck; sorry!

1 Like

Thanks, @pmk!

then there shouldn’t be a temporary unless the actual argument has a vector valued subscript or is the result of a function.

To be sure I understand, there is no way I can avoid the temporary copy if I pass to a subroutine a subset of an array arr with extents (1:n,1:n) as follows: call foo(arr(2:n-1,2:n-1)), correct?

A temporary isn’t required if the corresponding dummy argument to foo is assumed-shape, assumed-type, assumed-rank, or a pointer, and is not explicitly CONTIGUOUS.

If you don’t have an explicit interface for the subroutine, none of these can be true and you’re out of luck. If you have an explicit interface, but the corresponding dummy argument array has an explicit shape or an assumed size, you’re out of luck.

1 Like

Actually assumed-type alone (like C’s (void *) ) is not sufficient. Assumed-shape, assumed-rank, pointer and allocatable all get passed by descriptor that can describe a non-contiguous array section. Declaring the dummy argument CONTIGUOUS will also trigger a copy if the actual is not contiguous. As noted before, this is for “normal” sections, not vector subscripts. All of assumed-shape, assumed-rank, pointer, allocatable, or contiguous arguments require a visible interface.

It is helpful, if known, to declare the dummy as INTENT(IN) or INTENT(OUT). That can eliminate on of the copies if the interface can be determined by the compiler.

1 Like