user3225087
user3225087

Reputation: 225

Allocating array components of derived types

I have a type of something like the following

 type BOPinfo

     double precision, allocatable :: realQ4(:,:), realQ6(:,:)

  end type BOPinfo

I have been able to ascertain how to initialize elements in a derived type when the elements are real or integer scalars.

However, I can't figure out how to tell a variable of type BOPinfo what the size of the arrays realQ4 and realQ6 are, and maybe how to initialize them to zero. Any suggestions?

Upvotes: 1

Views: 1535

Answers (2)

francescalus
francescalus

Reputation: 32366

Allocatable (or pointer) type components cannot have default initialization. This applies to both deferred shape arrays and allocatable/pointer scalars. Allocatable components always have an initial status of "not allocated". Instead, one allocates and zeros the individual components separately from the object's declaration:

type(BOPinfo) test
integer n1, n2, m1, m2

allocate (test%realQ4(n1,m1), test%realQ6(n2,m2))
test%realQ4 = 0
test%realQ6 = 0

This is different from default (or explicit) initialization, and one may also set the value in a structure constructor (as in another answer).

Under Fortran 2003 there are other approaches for the dynamic size, including parameterized derived types (which are now widely supported in recent compiler versions).

Upvotes: 1

It is also possible to use a structure constructor to create a derived-type-valued expression. The constructor is a function with the same name as the type.

variable = BOPinfo(array1, array2)

where array1 and array2 are arrays with the appropriate rank. You can also pass null() if you want the component to be not allocated.

In Fortran 2008 you can even omit the allocatable components and they will have the status of not allocated.

Upvotes: 2

Related Questions