Fortran 在数组赋值时没有给出错误
Fortran not giving error on array assignment
我这里有一些测试代码并不像我怀疑的那样运行。我正在使用 gfortran 编译器。
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
我得到以下输出。
1 1
2 2 2 2
2 号前的尺码
1 1 1 1
2 2 2 2
4后的尺寸
为什么分配不同维度的数组时不会出错?
为什么 a 的尺寸变了?
这是一项名为 allocation on assignment 的功能。将数组分配给可分配数组时,它会自动调整大小。因此,在 a = b
之后,a
的大小应为 b
。
您可以通过 -Wrealloc-lhs
选项告诉编译器对此发出警告。
另请参阅此人条目:
-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
.
另请参阅 Steve Lionel 的相关博客条目 Doctor, it hurts when I do this。
我这里有一些测试代码并不像我怀疑的那样运行。我正在使用 gfortran 编译器。
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
我得到以下输出。
1 1
2 2 2 2
2 号前的尺码
1 1 1 1
2 2 2 2
4后的尺寸
为什么分配不同维度的数组时不会出错? 为什么 a 的尺寸变了?
这是一项名为 allocation on assignment 的功能。将数组分配给可分配数组时,它会自动调整大小。因此,在 a = b
之后,a
的大小应为 b
。
您可以通过 -Wrealloc-lhs
选项告诉编译器对此发出警告。
另请参阅此人条目:
-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
.
另请参阅 Steve Lionel 的相关博客条目 Doctor, it hurts when I do this。