Fortran array element order in memory

Viewed 87

I am using online IDE, and seems that none of them supports debugging. If I have a 4D array like below? How can I print all the elements of the array by the element's order in the memory?

Program Hello
    integer :: test(2,3,4,5), i1,i2,i3,i4, val;
    val = 0
    
    do i1=1,2
        do i2=1,3
            do i3=1,4
                do i4=1,5
                    test(i1, i2, i3, i4) = val
                    val = val +1
                end do
            end do
        end do
    end do

End Program Hello
2 Answers

Array/matrix memory in fortran is column-ordered, i.e. contiguous elements in memory are those of the leftmost dimension in your array.

You can print the whole one by just sending a print or write command of the whole array.

In this example, first we fill a 1D array with incremental indices; then, reshape them to a 4D array, so you can see how the 4D array items increment the leftmost dimension first:

program test_print
   use iso_fortran_env, only: output_unit
   implicit none

   integer :: test(2,3,4,5), global_index(2*3*4*5)
   integer :: i,j,k,l

   ! Fill 1D array with incremental values
   forall(i=1:size(global_index)) global_index(i) = i

   ! Reshape 1D array to 4D
   test = reshape(global_index,[2,3,4,5])

   ! Print whole array to screen
   ! Should print 1 2 3 4 5 6 7......
   print "(*(1x,i0))", test

   ! This is same as: 
   write(output_unit,"(*(1x,i0))") test

end program test_print

After your attempt at loading the array then try:

Test2 = RESHAPE(Test,/120/)
Do I = 1, 120
WRITE… test2

That will reform the array into a linear vector or 1D array, and you can see how the contiguous array is stored.

Related