Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between POINTER and ALLOCATABLE

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))
like image 297
Stefano Borini Avatar asked Oct 26 '10 11:10

Stefano Borini


1 Answers

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.

like image 80
Wildcat Avatar answered Oct 28 '22 16:10

Wildcat