在fortran中传递指针参数 [英] passing pointer arguments in fortran

查看:770
本文介绍了在fortran中传递指针参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 程序foo 

INTEGER :: x
REAL(KIND = 8),TARGET,DIMENSION(0:10):: array
REAL(KIND = 8),POINTER,DIMENSION(:) :: ptr

ptr =>数组

CALL bar(ptr)

END程序foo

子程序bar(ptr)

REAL(KIND = 8),POINTER,DIMENSION(:) :: ptr
INTEGER x
DO x = 0,10
ptr(x)= 2 // seg故障
ENDDO

END SUBROUTINE bar

如果我声明 ptr in bar 作为 REAL(KIND = 8),DIMENSION(0:10)。但总的来说,我可能不知道传入数组的大小,那么是否有办法将 ptr 声明为某个数组的指针?我正在用 gfortran 来编译

解决方案

参数是一个指针,那么在任何调用范围中都需要显式接口。



(有很多事情需要显式接口,虚拟指针只有一个。 )

您可以通过在子程序中为您的子程序添加一个接口块来为您提供明确的接口。另一种远远更好的选择是将子程序放入模块中,然后在主程序中使用该模块。第三种方法是使子程序成为调用范围的内部过程。



从Fortran 2003开始,如果您打算将指针指向不同的位置,则只应使用指针的东西。如果您只是使用指针来表示某个值的行为,那么您应该使用allocatables。


I am wondering what is the proper way to write the following code?

PROGRAM foo

  INTEGER :: x
  REAL(KIND=8), TARGET, DIMENSION(0: 10) :: array
  REAL(KIND=8), POINTER, DIMENSION(:) :: ptr

  ptr => array

  CALL bar(ptr)

END PROGRAM foo

SUBROUTINE bar (ptr)

  REAL(KIND=8), POINTER, DIMENSION(:) :: ptr                                                                                                                                                                                                                  
  INTEGER x
  DO x =0, 10
    ptr(x) = 2 // seg faults
  ENDDO

END SUBROUTINE bar

It works if I declare ptr in bar as REAL(KIND=8), DIMENSION(0:10). But in general I might not know the size of the passed-in array, so is there a way to declare ptr to be a pointer to some array? I am compiling this with gfortran

解决方案

If a procedure has a dummy argument that is a pointer, then an explicit interface is required in any calling scope.

(There are numerous things that require an explicit interface, a pointer dummy is but one.)

You can provide that explicit interface yourself by putting an interface block for your subroutine inside the main program. An alternative and far, far, far better option is to put the subroutine inside a module and then USE that module in the main program. A third alternative is to make the subroutine an internal procedure of the calling scope.

As of Fortran 2003, you should only use pointers if you intend to point the pointer at different things. If you are just using the pointer for something that really just behaves like a value, then you should use allocatables instead.

这篇关于在fortran中传递指针参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆