Fortran

Guide To Learn

Allocating arrays of a certain size or range

In the previous few sections, we’ve learned how to declare and initialize dynamic arrays. However, what if we need to assign values to individual array elements, one by one, in a loop? This will be the case as we load the data from CSV files into arrays–we’ll iterate over records in files, and assign values to array elements one at a time. However, we don’t really have a way to initialize the data arrays like we did with stock_symbols in listing 5.3. Note that implicitly allocating by assigning an empty array [integer ::] or [real ::] won’t work here because we may need to index elements of an array in some order other than just appending values. This calls for a more explicit mechanism to allocate the array without assigning known values to it:

real, allocatable :: a(:)    ❶
integer :: im = 5
allocate(a(im))              ❷

❶ Declares a real, dynamic array a

❷ Allocates the array a with size im

This code tells the program to reserve memory for the array a of size im, in this case 5. When invoked like this, a will, by default, have a lower bound of 1, and an upper bound of im. The lower bound of 1 is the default, similar to what you’ll find in Julia, R, or MATLAB. This is unlike C, C++, Python, or JavaScript, where array or list indices begin with 0.

However, Fortran doesn’t impose a constraint to the start index being 1, unlike Python, where the first index is always 0. You can specify the lower and upper bounds in the allocation statement:

integer :: is = -5, ie = 10
allocate(a(is:ie))           ❶

❶ Allocates the array a with a range from is to ie

Notice that I used a colon (:) between is and ie to specify the range. This range is inclusive (unlike in Python!), so the size of a is now ie - is + 1–in this case 16.

Inquiring about array bounds

You can use the built-in functions lbound and ubound to get the lower and upper bound, respectively, of any array.

Allocating arrays of a certain size or range

Leave a Reply

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

Scroll to top