Fortran

Guide To Learn

Allocating an array from another array

It’s also possible to dynamically allocate an array based on the size of another array. The allocate statement accepts two optional arguments:

  • mold–A variable or an expression that has the same type as the object being allocated
  • source–Equivalent to mold, except that the values of source are used to initialize the object being allocated

For example, allocating a from b using mold will reserve the space in memory for a but won’t initialize its elements:

real, allocatable :: a(:), b(:)
allocate(b(10:20))
allocate(a, mold=b)      ❶
a = 0                    ❷

❶ Allocating from mold won’t initialize a.

❷ Initializes values separately

However, if we allocate a from b using source, it will be allocated and initialized with values of b:

real, allocatable :: a(:), b(:)
b = [1.0, 2.0, 3.0]
allocate(a, source=b)         ❶

❶ Allocates and initializes a with values of b

Tip No matter how you choose to allocate your arrays, always initialize them immediately after allocation. This will minimize the chance of accidentally using uninitialized arrays in expressions. Although Fortran will allow you to do this, you’ll likely end up with gibberish results.

You may have noticed that when describing the array constructors in section 5.2.2, I initialized arrays without explicitly allocating them with an allocate statement (see, for example, listings 5.4 and 5.5). How come? You may rightfully ask, do I need to explicitly allocate arrays or not? Since Fortran 2003, we’ve had available a convenient feature of the language called allocation on assignment.

Allocating an array from another array

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top