user1638145
user1638145

Reputation: 2049

Fortran: Array of unknown size in type

Perhaps this is a really stupid question and one should really do this differently, but: Is there a possibility to have something like

type food
 INTEGER :: NBananasLeft(NBananaTypes)
 INTEGER :: NApplesLeft(NAppleTypes)
end type food

where NBananaTypes and NAppleTypes is not known at compilation time?

Upvotes: 4

Views: 2122

Answers (1)

In Fortran 90-95:

type food
 INTEGER,pointer :: NBananasLeft(:)
 INTEGER,pointer :: NApplesLeft(:)
end type food

you must allocate the arrays yourself using allocate(var%NBananasLeft(NBananaTypes))).

In Fortran 2003:

type food
 INTEGER,allocatable :: NBananasLeft(:)
 INTEGER,allocatable :: NApplesLeft(:)
end type food

you must also allocate the arrays yourself using allocate(var%NBananasLeft(NBananaTypes))), but you avoid the possibility of memory leaks.

In Fortran 2003 by parametrized data types (only a few compilers support that):

type food(NBananaTypes,NAppleTypes)
 integer,len :: NBananaTypes,NAppleTypes
 INTEGER :: NBananasLeft(NBananaTypes)
 INTEGER :: NApplesLeft(NAppleTypes)
end type food

Upvotes: 4

Related Questions