How do I access last item in an array in Fortran?

2020-02-10 02:16发布

问题:

In Matlab, end index lets me access a last item.

> array = [1 2 3 4 5 6 7];
> array(end)
ans =  7

How do I do the same in Fortran?

program hello
   integer array(7)
   array = (/1, 2, 3, 4, 5, 6, 7/)
!print *, array(end)
!               1
!Error: Legacy Extension: REAL array index at (1)

! print *, array(-1)
!                1
!Warning: Array reference at (1) is out of bounds (-1 < 1) in dimension 1

! print *, array(0)
!                1
!Warning: Array reference at (1) is out of bounds (0 < 1) in dimension 1
end program Hello

回答1:

array ( ubound (array) )

size will only work if the array is 1-indexed.



回答2:

there is no such convenience notation, you need to do this

 array(size(array))

in older fortran versions you dont even have size() and need to track the dimension yourself

worth a note fortran arrays can be defined to have negative indices, so the end notation used in some other languages would be ambiguous