Procedure pointers in Fortran [duplicate]

谁都会走 提交于 2020-04-16 02:10:51

问题


I am trying to have a generic subroutine event() and a procedure pointer to this generic subroutine, event_i. Then I would like to create any subroutine (like hello_wolrd in the following code) and point to this created subroutine. Can you help me to understand why the first code does not work while the second one does work? The error I get with the first version of the code is: Program received signal SIGSEGV: Segmentation fault - invalid memory reference. I would like to use the first version because then I can use inside the subroutine hello_world any variable defined in the main while in the second case I have to pass the variable to te subroutine and it cannot be defined anymore as a generic subroutine event(), which does not have input.

First version(not working)

program foo

  implicit none

  interface 
    subroutine event()
    end subroutine event
  end interface

   procedure(event), pointer :: event_i => Null()
   event_i => hello_world
   call event_i

contains

  subroutine hello_world()
    print *, 'hello_world'
  end subroutine

end program foo

Second version (working):

program foo

  implicit none

  interface 
    subroutine event()
    end subroutine event
    subroutine hello_world()
    end subroutine hello_world
  end interface

   procedure(event), pointer :: event_i => Null()
   event_i => hello_world
   call event_i

end program foo

subroutine hello_world()
  print *, 'hello_world'
end subroutine

I am using gfortran and the compiler version is

gfortran --version
GNU Fortran (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609

回答1:


This is a slightly nontrivial modification, it works well with gfortran:

program foo

  implicit none

  abstract interface 
    subroutine event()
   end subroutine event
 end interface

  procedure(event), pointer :: event_i
  procedure(event), pointer :: event_j


 event_i => hello_world
 event_j => hello_world2

 call event_i
 call event_j


contains

 subroutine hello_world()
    print *, 'hello_world'
 end subroutine


 subroutine hello_world2()
   print *, 'HELLO_WORLD'
 end subroutine

end program foo


来源:https://stackoverflow.com/questions/50717926/procedure-pointers-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!