An array whose size is not defined at the compilation time but is defined at run time is known as a dynamic array.
For the declaration of this array, we use the keyword allocatable
. These arrays are quite helpful to accurately use the required memory at the required time.
Let’s discuss the basic syntax of dynamic arrays.
type, dimension(: ), allocatable :: name
type, dimension(:,: ), allocatable :: name
To create n-dimensional
arrays, repeat :
times in the dimension()
method.
After defining the dimension of an array, we have to use the allocate()
function to allocate the memory to the defined array.
Allocate(arr1(v1))
We can also use the deallocate()
function to free the memory location.
Deallocate(arr1)
Integer, dimension ( : ), Allocatable :: arr1Allocate(arr1(v1))Deallocate(arr1)
To initialize a two-dimensional array, use the code below.
Integer, dimension ( : , : ), Allocatable :: arr2
To allocate
the memory space:
Allocate(arr2(v1 , v2))
To deallocate
:
Deallocate(arr2)
Integer, dimension ( : , : ), Allocatable :: arr2Allocate(arr2(v1 , v2))Deallocate(arr2)
The code snippet below demonstrates the use of dynamic arrays.
# While making exercises "package Test;" needs to be the first line of code.program example_daimplicit nonereal, dimension (:,:), allocatable :: arr1integer :: v1, v2print*, "please enter array size"read*, v1, v2allocate ( arr1(v1,v2) )arr1(v1,v2) = v1 * v2print*, "arr1(",v1,",",v2,") = ", arr1(v1,v2)deallocate (arr1)end program example_da