Pointers in Fortran (Part 2) – arrays

Now what about pointers and arrays in Fortran? Well they can be dealt with in a similar fashion. Consider the following code:

integer, target :: r(10)
integer, pointer :: pr(:)
pr => r

This implies that any reference to pr is identical to a reference to r. But it is also possible to do this:

pr => r(3:8)

Here pr is an array with 6 elements with pr(1) the same as r(3). There is also a second way of allocating arrays, through use of the allocateallocation combination. Single dimension dynamic arrays can be specified in Fortran in the following manner:

integer, dimension(:), allocatable :: d

The colon specifies one-dimension, but not the size of the dimension, this is allocated later in the following manner:

integer :: dLen, i
write (*,*) "Number of elements in the array: "
read (*,*) dLen
allocate(d(dLen))

Now elements can be input directly into the array:

write (*,*) "Enter the elements: "
do i = 1,dLen
    read (*,*) d(i)
end do

Note that allocatable arrays are automatically deallocated when they go out of scope.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s