Casting a 2D array into a 1D array without copying data

Casting a 2D array into a 1D array without copying data

Hi All,

I have the folowing problem. In my F2003 code I use 2 dimensional arrays to store some data. I need to pass this data to some external code which expects a pointer to an 1D array. Because these arrays are big I do not want to copy the data but this causes a lot op problems for me since whatever I try it get compiler errors or a crash at runtime.

Does sombody knows a way around these compiler checks?

Here is some code to illustrate my problem

Program main
    integer, pointer :: Array2D(:,:)
    integer, pointer :: Array1D(:)
    
    allocate(Array2D(2,2))
    Array2D(1,1) = 1
    Array2D(2,1) = 2
    Array2D(1,2) = 3
    Array2D(2,2) = 4
    
    !!! Copies data
    allocate(Array1D(4))
    Array1D(1:4) = Transfer(Array2D,Array1D)  !!! Works fine but copies data
    write(*,*) Array1D(1:4)
    deallocate(Array1D)

   !!! Attempt 1
    Array1D(1:4) => Array2D(:,:) !!! Compiler error:  If a bound remapping list is specified, data target must be simply contiguous or of rank one.   [ARRAY2D]

    !!! Attempt 2
    Array1D => Transfer(Array2D,Array1D) !!! Compiler Error:  When the target is an expression it must deliver a pointer result.
    write(*,*) Array1D(1:4)
end program   

publicaciones de 4 / 0 nuevos
Último envío
Para obtener más información sobre las optimizaciones del compilador, consulte el aviso sobre la optimización.

use, intrinsic :: iso_c_binding
...
call c_f_pointer (c_loc(array2), array1, [4])

This will make array1 point to the same storage as array2.

Steve - Intel Developer Support

    integer, allocatable, target :: Array2D(:,:)
    integer, pointer :: Array1D(:)
    Allocate(Array2D(2,2))
    Array2D(1,1) = 1
    Array2D(2,1) = 2
    Array2D(1,2) = 3
    Array2D(2,2) = 4
    Array1D(1:size(Array2D)) => Array2D

Jim Dempsey

www.quickthreadprogramming.com

Another way you could make Array2D simply contiguous is by giving it the CONTIGUOUS attribute.

Deje un comentario

Por favor inicie sesión para agregar un comentario. ¿No es socio? Únase ya