指针数组fortran [英] array of pointers fortran

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

问题描述

同样,Fortran中的指针数组.很好,我有一个派生类型:

Again, array of pointers in Fortran. So well, I've a derived type:

type :: t_context_pointer  
    type(t_context),pointer :: p_ctx  
end type t_context_pointer

当我在主程序中这样做时:

When I do in the main program:

type(t_context_pointer),allocatable :: tab_ctx_ptr(:)  
type(t_context),allocatable,target :: ctx  
allocate(tab_ctx_ptr(1))  
allocate(ctx)  
tab_ctx_ptr(1)%p_ctx=>ctx

有效.但是当我使用函数调用时:

it works. But when I use a function call:

type(t_context_pointer),allocatable,target :: tab_ctx_ptr(:)
allocate(tab_ctx_ptr(n))
call alloc_ctx(tab_ctx_ptr,n,1)

与其他地方一起:

subroutine alloc_ctx(tab_ctx_ptr,n,i)
    integer,intent(in) :: n,i
    type(t_context_pointer),intent(inout) :: tab_ctx_ptr(n)

    type(t_context),allocatable,target :: ctx

    allocate(ctx)
    tab_ctx_ptr(i)%p_ctx=>ctx
end subroutine

稍后在代码中出现seg_fault.这里有什么问题吗?

it seg_fault later in the code. Is there something wrong here?

推荐答案

ctx 在子例程 alloc_ctx 的范围内,并在离开子例程后立即释放.稍后(通过指针)对其进行访问将导致段错误.

ctx is in the scope of the subroutine alloc_ctx and gets deallocated as soon as you leave the subroutine. Accessing it later (by means of the pointer) will cause a segfault.

在第一个示例中,您在主程序中分配了 ctx ,因此其作用域将一直到程序结束.

In the first example, you allocate ctx in the main program, so its scope will be until the end of the program.

为什么不分配 tab_ctx_ptr(i)%p_ctx :

subroutine alloc_ctx(tab_ctx_ptr,n,i)
    integer,intent(in) :: n,i
    type(t_context_pointer),intent(inout) :: tab_ctx_ptr(n)

    allocate(tab_ctx_ptr(i)%p_ctx)
end subroutine

关于释放:您可以使用类似这样的方法来释放所有指针(而不是数组本身):

As for deallocation: You could use something like this to deallocate all pointers (but not the array itself):

subroutine dealloc_ctx(tab_ctx_ptr,n)
    integer,intent(in) :: n
    type(t_context_pointer),intent(inout) :: tab_ctx_ptr(n)
    integer            :: i

    do i=1,n
      ! Check whether the current element has an allocated element and 
      ! deallocate if necessary. 
      if ( associated(tab_ctx_ptr(i)%p_ctx) ) deallocate(tab_ctx_ptr(i)%p_ctx)
    enddo ! i
end subroutine

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

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