Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fortran: Pointers in Common Blocks

I’m unexperienced in Fortran. I’m trying to declare a memory pointer in a file named ‘common’, then allocate memory for that pointer in a file named "main.f", then call a subroutine from another file named "PrintArray.f". The whole thing seg faults in "PrintArray.f". How can I correct this?

This is the file named ‘common’:

REAL, DIMENSION (:), POINTER :: p_dynamicArray

This is the first Fortran file (main.f):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  PROGRAM Main
  include 'common'
  INTEGER :: ArraySize, i
  ArraySize = 4

  ALLOCATE (p_dynamicArray(ArraySize))

  DO i = 1, ArraySize
      p_dynamicArray(i) = i
  END DO

  call PrintArray()

  DEALLOCATE (p_dynamicArray)
  END

This is the second Fortran file (PrintArray.f):

  subroutine PrintArray()
  include 'common'
  INTEGER :: i

  DO i = 1, 4
      WRITE(0,*) "PrintArray.f: ", p_dynamicArray(i)
  END DO

  end

>Solution :

"include" has never been part of the Fortran standard (WHOOPS – SORRY, THAT’S WRONG!) – but all that it would do is simply place the contents of the file into the source code at that place.

You are NOT using common blocks, so nothing is shared between program units – PrintArray would have a completely separate pointer variable to that in main, one that hadn’t been allocated or set.

If you use modules to share data then you can do this:

MODULE modcommon
   REAL, DIMENSION (:), POINTER :: p_dynamicArray
END MODULE modcommon


PROGRAM Main
  USE modcommon                        ! Allows shared content
  implicit none
  INTEGER :: ArraySize, i
  ArraySize = 4

  ALLOCATE (p_dynamicArray(ArraySize))

  DO i = 1, ArraySize
      p_dynamicArray(i) = i
  END DO

  CALL PrintArray()

  DEALLOCATE (p_dynamicArray)
END PROGRAM Main


SUBROUTINE PrintArray()
  USE modcommon                        ! Allows shared content
  implicit none
  INTEGER :: i

  DO i = 1, 4
      WRITE(*,*) "PrintArray.f: ", p_dynamicArray(i)
  END DO
END SUBROUTINE PrintArray

You can break that up into source (.f90) files. Make sure the one containing the module is compiled first.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading