4

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Just to add; IRO-bot's answer correctly gives you a derived type which contains arrays of ints, floats, and chars. If you wanted an array of (type containing int + float + char), you'd define your type as above but without DIMENSIONS on the types - eg, a single int, float, and char - and then define eg. TYPE(mytype), DIMENSION(10) :: a or TYPE(mytype), ALLOCATABLE, DIMENSION(:), :: a and later allocate(a(10)).
@JonathanDursi Thanks for the suggestion - I added this to the answer.
Thanks very much, guys. This is very helpful. So using derived types I can construct from the mainstream/default types my own type, the shape/dimension of which I can state in the definition or, even better, allocate it later based on how the program runs. Sweet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.