0

I am trying to understand some Fortran code. There is a subroutine which takes a 2D array as input. Then this subroutine is called from somewhere else, but is passed the first element of a 2D array instead of the array itself. However, the subroutine seems to treat this input as if it were just the 2D array itself and is able to access all of its elements. This makes it seem like the subroutine actually accepts a pointer to a scalar, like how you can pass arrays in C/C++.

I have made a small example that demonstrates what I mean:

program main
    dimension k(2, 2);
    k(1, 1) = 1; k(1, 2) = 2
    k(2, 1) = 4; k(2, 2) = 3
    call test(2, k(1, 1))
end program

subroutine test(n, k)
    dimension k(n, n)
    do i=1, n
        write(*, '(2(I1 X))') (k(i,j), j=1,n)
    end do
end subroutine test

This program outputs the following:

1 2
3 4

Can someone explain this to me?

D. de Vries
  • 417
  • 3
  • 12

1 Answers1

1

This seems to be a hack on the compiler, as you pass actually the array as a 2D (1,1) element (see http://astroa.physics.metu.edu.tr/MANUALS/intel_ifc/mergedProjects/optaps_for/fortran/optaps_prg_arrs_f.htm Intel seems to have changed their links...). As you can see at the bottom, you pass a fixed-shape array.

Then in the function itself, you hack the compiler and set the size of the array dimension k(n, n), so that's a different value than what you specified.

This is probably Fortran 77 code, in Fortran 90 and upwards, you would not do something as bad as this, as you can and should pass the array with the sizes directly to the function and it uses them directly.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • The code I'm trying to understand is indeed Fortran 77 code. And in fact, the actual subroutine that I am dealing with takes the dimensions of the array as input arguments, like you said. Strangely, the authors of this code do pass the sizes of the full array, but only the first element of the array itself. But it seems like they expect the function to handle the full array anyway. – D. de Vries Dec 04 '18 at 21:52
  • 6
    This is called sequence association and it is perfecrly legal. And handy even today like when sendin and receiving MPI subarray derived types in multidimensiinal arrays. – Vladimir F Героям слава Dec 04 '18 at 22:07