Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28435 Discussions

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

gert_massa
Beginner
682 Views

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   

0 Kudos
3 Replies
Steven_L_Intel1
Employee
682 Views

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.

0 Kudos
jimdempseyatthecove
Honored Contributor III
682 Views

[fortran]

    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
[/fortran]

Jim Dempsey

0 Kudos
JVanB
Valued Contributor II
682 Views

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

0 Kudos
Reply