5

Is there a difference between

integer, intent(in) :: n
integer, dimension(:), allocatable :: a
allocate(a(n))

and

integer, intent(in) :: n
integer, dimension(n) :: a

In which situation would we use the first version? Perhaps I misunderstood allocatable array, is the second version even an allocatable array?

Fortranner
  • 2,525
  • 2
  • 22
  • 25
Fabricator
  • 12,722
  • 2
  • 27
  • 40

2 Answers2

8

The second case indeed doesn't have a allocatable. It is, however, an automatic object.

Ignoring the practical differences in memory use at the implementation level, there is a big difference. Yes, each a is (assuming things not explicitly stated in the question) a local variable which is, after the allocate and the automatic creation, of size n, but in the first case it is allocatable. It can be deallocated, reallocated (perhaps to a different size), and deallocated again. And so on.

The automatic object (second case) cannot be.

francescalus
  • 30,576
  • 16
  • 61
  • 96
2

The first case is an allocatable array. The number of elements in the array may be dynamically allocated or reallocated at runtime at any scope.

The second case is an automatic array of a fixed number of elements defined by the dummy argument. Its size can only be changed locally within the procedure it is called in, according to the size passed in the dummy argument.

paisanco
  • 4,098
  • 6
  • 27
  • 33