difference between POINTER and ALLOCATABLE

北慕城南 提交于 2019-12-10 14:54:07

问题


what is the difference between these two codes

type Foo
   real, allocatable :: bar(:)
end type

and

type Foo
   real, pointer :: bar(:)
end type

in particular when it comes to the following code:

type(Foo) :: myfoo
allocate(myfoo%bar(10))

回答1:


I do not see any principal difference in that scenario.

In general, ALLOCATABLE arrays are more efficient. But in Fortran 90/95 POINTER arrays were more flexible. For example, it was not possible to use ALLOCATABLE arrays as components of derived types. Fortran 2003 fixed that issue. So use ALLOCATABLE arrays when you can.

EDIT

Just want to mention significant difference in behavior of the program on the attempt to allocate already allocated entity. If the entity is ALLOCATABLE you'll get run-time error. The program

PROGRAM main

  IMPLICIT NONE

  TYPE :: foo
    REAL, DIMENSION(:), ALLOCATABLE :: bar
  END TYPE foo

  TYPE(foo) :: my_foo

  ALLOCATE (my_foo%bar(10))
  ALLOCATE (my_foo%bar(10))

END PROGRAM main

compiled with gfortran results in such error message:

Fortran runtime error: Attempting to allocate already allocated variable 'my_foo'

In contrast you can do such things with POINTERs.



来源:https://stackoverflow.com/questions/4023371/difference-between-pointer-and-allocatable

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