Reputation: 1750
Exactly the same questions as Create an array with elements of different types, except how to do this in Fortran?
Say I want an array with the first dimension an integer
type, the second real
and the third character
(string) type. Is it possible to create a "struct
" in Fortran too?
Thanks.
Upvotes: 4
Views: 5313
Reputation: 6241
Here is an example program of a derived type use:
TYPE mytype
INTEGER,DIMENSION(3) :: ints
REAL,DIMENSION(5) :: floats
CHARACTER,DIMENSION(3) :: chars
ENDTYPE mytype
TYPE(mytype) :: a
a%ints=[1,2,3]
a%floats=[1,2,3,4,5]
a%chars=['a','b','c']
WRITE(*,*)a
END
The output is:
1 2 3 1.000000 2.000000
3.000000 4.000000 5.000000 abc
EDIT: As per suggestion by Jonathan Dursi:
In order to have an array where each element has a int, float and char element, you would do something like this:
TYPE mytype
INTEGER :: ints
REAL :: floats
CHARACTER :: chars
ENDTYPE mytype
TYPE(mytype),DIMENSION(:),ALLOCATABLE :: a
ALLOCATE(a(10))
You would then reference your elements as, e.g. a(i)%ints
, a(i)%floats
, a(i)%chars
.
Related answer is given in Allocate dynamic array with interdependent dimensions.
Upvotes: 9