Any type can be declared as an array using either the dimension attribute or by just indicating directly the dimension
(s) of the array:
! One dimensional array with 4 elements
integer, dimension(4) :: foo
! Two dimensional array with 4 rows and 2 columns
real, dimension(4, 2) :: bar
! Three dimensional array
type(mytype), dimension(6, 7, 8) :: myarray
! Same as above without using the dimension keyword
integer :: foo2(4)
real :: bar2(4, 2)
type(mytype) :: myarray2(6, 7, 8)
The latter way of declaring multidimensional array, allows the declaration of same-type different-rank/dimensions arrays in one line, as follows
real :: pencil(5), plate(3,-2:4), cuboid(0:3,-10:5,6)
The maximum rank (number of dimensions) allowed is 15 in Fortran 2008 standard and was 7 before.
Fortran stores arrays in column-major order. That is, the elements of bar
are stored in memory as follows:
bar(1, 1), bar(2, 1), bar(3, 1), bar(4, 1), bar(1, 2), bar(2, 2), ...
In Fortran, array numbering starts at 1 by default, in contrast to C which starts at 0. In fact, in Fortran, you can specify the upper and lower bounds for each dimension explicitly:
integer, dimension(7:12, -3:-1) :: geese
This declares an array of shape (6, 3)
, whose first element is geese(7, -3)
.
Lower and upper bounds along the 2 (or more) dimensions can be accessed by the intrinsic functions ubound
and lbound
. Indeed lbound(geese,2)
would return -3
, whereas ubound(geese,1)
would return 12
.
Size of an array can be accessed by intrinsic function size
. For example, size(geese, dim = 1)
returns the size of first dimension which is 6.