user3918138
user3918138

Reputation: 13

Is it necessary to allocate an allocatable array?

I have a simple question regarding derived types and allocated arrays. Suppose we have defined the type

type demo_type
        real(kind=8),allocatable :: a(:)
end type demo_type

and the function

function demo_fill(n) result(b)
        integer, intent(in) :: n
        real(kind=8) :: b(n)
        b = 1.d0
end function demo_fill

Is it correct to write in the main program

type(demo_type) :: DT
DT%a = demo_fill(3)

Or is it necessary to first allocate DT%a to prevent accidentally overwriting other variables in memory?

type(demo_type) :: DT
allocate(DT%a(3))
DT%a = demo_fill(3)

They both compile, but I am wondering which is the correct way. Thanks!

Upvotes: 1

Views: 280

Answers (1)

In Fortran 2003 any allocatable array can be allocated automatically on assignment.

In your case

DT%a = demo_fill(3)

causes DT%a to be automatically allocated to the shape of the right hand side, which is the result of the function, if it has not been allocated to this shape previously.

This behavior is standard, but some compilers do not enable it by default, notably the Intel Fortran. You must use special compiler flags to enable it (-standard-semantics, -assume realloc_lhs)

As a side note, kind=8 does not mean 8-byte reals on all compilers, and this usage is frowned upon (see https://stackoverflow.com/a/856243/721644).

Upvotes: 7

Related Questions