Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array and pointer shapes

Can someone explain me why the following program doesn't work, and how to make it work? In the main program I allocate a pointer, in the subroutine sub I look for the shape of the array and get wrong values.

  program test
    real, pointer, dimension(:,:,:) :: arr
    allocate(arr(3,5,7))
    print *, "In test: ",shape(arr)
    call sub(arr)
    print *, "Back in test: ",shape(arr)
  end program test

  subroutine sub(arr)
    real, pointer, dimension(:,:,:) :: arr
    print *, "In sub: ",shape(arr)
  end subroutine

Output:

 In test:            3           5           7
 In sub:     12694064           1           3
 Back in test:            3           5           7

Thanks

PS: I'm using gfortran (gcc 4.4.3)

EDIT: with gfortran 4.6, this code simply doesn't compile. I get the error:

Dummy argument 'arr' of procedure 'sub' at (1) has an attribute that requires an explicit interface for this procedure

like image 662
sunmat Avatar asked Jan 17 '23 10:01

sunmat


1 Answers

To use the "advanced" features of Fortran 90/95/2003/2008 the interfaces of procedures (subroutines and functions) should be known to the caller. This is called "explicit" interfaces. gfortran 4.6 told you what the problem was. The easiest way is to put your procedures in a module. Try this:

module mysubs
implicit none
contains
  subroutine sub(arr)
    real, pointer, dimension(:,:,:) :: arr
    print *, "In sub: ",shape(arr)
  end subroutine
end module mysubs

program test
    use mysubs
    implicit none
    real, pointer, dimension(:,:,:) :: arr
    allocate(arr(3,5,7))
    print *, "In test: ",shape(arr)
    call sub(arr)
    print *, "Back in test: ",shape(arr)
end program test
like image 123
M. S. B. Avatar answered Jan 25 '23 01:01

M. S. B.