next up previous contents
Next: Parameterized Data Types Up: Survey of the New Previous: Derived Types and Generic

Pointers and Dynamic Data Structures

 

Fortran 90 contains 3 types of dynamic data: allocatable arrays, automatic data objects, and pointers. Allocatable arrays were described briefly in section 1.2 and apply only to arrays. Automatic data objects consist of those objects that are created on entry to a subprogram and destroyed upon exit. Pointers may be used with scalar or array quantities of any type and are used to construct dynamic structures such as linked lists and trees.

The following program illustrates how a dynamic data structure can be declared and manipulated.

program LinkedList
   type node
      real data
      type( node ), pointer :: next
   end type node
 
   type( node ), pointer :: list, current

   nullify( list )   ! Initialize list to point to no target.

   ! Place two elements in the list.
   allocate( list )   ! Reserve space for first node.
   call random_number( list%data )   ! Initialize data portion.
   allocate( list%next )   ! Reserve space for second node.
   call random_number( list%next%data )   ! Initialize data portion.
   nullify( list%next%next )   ! Initialize next to point to no target.

   ! Output the list.
   current => list   ! Assign target of list to target of current.
   do while ( associated( current ) )
      print *, current%data
      current => current%next
   end do

end program LinkedList



next up previous contents
Next: Parameterized Data Types Up: Survey of the New Previous: Derived Types and Generic