Section Arrays: Allocate from Source

Section Arrays: Allocate from Source#

Adapted from: gjbex/Fortran-MOOC

This program demonstrates allocating an array from a source array.#

program allocate_from_source
    use, intrinsic :: iso_fortran_env, only : error_unit
    implicit none
    integer, dimension(3, 2) :: A
    integer, dimension(:, :), allocatable :: B
    integer :: i, status

    A = reshape([ (i, i=1, size(A)) ], shape(A))
    allocate(B, source=A, stat=status)
    if (status /= 0) then
        write (unit=error_unit, fmt='(A)') 'error: can not allocate array'
        stop 1
    end if
    print *, 'The matrix A contains:'
    do i = 1, size(A, 1)
        print '(*(I4))', A(i, :)
    end do
    print *
    print *, 'The matrix B contains:'
    do i = 1, size(A, 1)
        print '(*(I4))', A(i, :)
    end do
    deallocate (B)
end program allocate_from_source

The above program is compiled and run using Fortran Package Manager (fpm):

import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "Fortran_Code/Section_Arrays_Allocate_from_Source"
os.chdir(code_dir)
build_status = os.system("fpm build 2>/dev/null")
exec_status = os.system("fpm run 2>/dev/null")
 The matrix A contains:
   1   4
   2   5
   3   6

 The matrix B contains:
   1   4
   2   5
   3   6