I've got some test code here that is not acting as I would suspect. I'm using the gfortran compiler.
program test
implicit none
integer, allocatable, dimension(:) :: a
integer, allocatable, dimension(:) :: b
allocate(a(2))
allocate(b(4))
a = 1
b = 2
write(*,*) a
write(*,*) ' '
write(*,*) b
write(*,*) ' '
write(*,*) 'a size before', size(a)
a = b
a = 1
write(*,*) a
write(*,*) ' '
write(*,*) b
write(*,*) ' '
write(*,*) 'a size after', size(a)
end program test
And I get the following output.
1 1
2 2 2 2
a size before 2
1 1 1 1
2 2 2 2
a size after 4
Why do I not get an error when assigning arrays of different dimensions? Why is the size of a changed?
This is a feature called allocation on assignment. When assigning an array to an allocatable array, this gets automatically resized. So after a = b
, a
is expected to have the size of b
.
You can tell the compiler to warn about this via the -Wrealloc-lhs
option.
See also this man entry:
-frealloc-lhs
An allocatable left-hand side of an intrinsic assignment is automatically (re)allocated if it is either unallocated or has a different shape. The option is enabled by default except when
-std=f95
is given. See also-Wrealloc-lhs
.
Also see the related blog entry Doctor, it hurts when I do this by Steve Lionel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With