Clicky

Fortran Wiki
pointer_example

An example of pointer usage in Fortran:

program pointer_example
    real, target  :: a, b, c
    real, pointer :: p, q

    ! Define some values
    a = 3.1416
    b = 2.7182
    c = 0.5772

    ! The following pointer associations result in
    ! a = p = 3.1416 and b = q = 2.7182
    p => a
    q => b
    call print_values()

    ! If we use conventional assignment, all four variables
    ! a, b, p, and q will be 3.1416
    q = p
    call print_values()

    ! Alternatively, if we can use pointer association
    ! to set p = c = 0.5772 without changing a, b, or q.
    p => c
    call print_values()

contains

  subroutine print_values()
    print *, 'Values:'
    print *, 'a = ', a
    print *, 'b = ', b
    print *, 'c = ', c
    print *, 'p = ', p
    print *, 'q = ', q
  end subroutine print_values

end program pointer_example

The output of this program is:

 Values:
 a =    3.141600    
 b =    2.718200    
 c =   0.5772000    
 p =    3.141600    
 q =    2.718200    
 Values:
 a =    3.141600    
 b =    3.141600    
 c =   0.5772000    
 p =    3.141600    
 q =    3.141600    
 Values:
 a =    3.141600    
 b =    3.141600    
 c =   0.5772000    
 p =   0.5772000    
 q =    3.141600    

category: code