来自转置数组的源分配
Sourced allocation from transposed array
我正在尝试了解我在代码中遇到的错误。当尝试使用数组的转置分配数组时,我在代码中使用了带有 source=transpose(original_array) 的分配语句。但是,使用此方法我没有得到预期的结果。似乎索引关闭了一个并且跳过了源数组的第一行。
示例:
program testalloc
real*8, allocatable :: a(:, :)
real*8, allocatable :: b(:, :)
allocate(b(2, 3))
b(1, :) = [1, 2, 3]
b(2, :) = [4, 5, 6]
call printmat(b)
a = transpose(b)
call printmat(a) ! Good
deallocate(a)
allocate(a(3, 2), source=transpose(b))
call printmat(a) ! Bad
deallocate(a)
allocate(a(3, 2))
a = transpose(b)
call printmat(a) ! Good
contains
subroutine printmat(mat)
real*8, intent(in) :: mat(:, :)
integer :: i
write(*,*) 'print'
do i = 1, size(mat, 1)
write(*,*) mat(i, :)
end do
end subroutine
end program
这给出了
print
5.0000000000000000 3.0000000000000000
6.0000000000000000 0.0000000000000000
3.2114266979681025E-322 5.0000000000000000
使用 gfortran(gcc 版本 7.3.0(Ubuntu 7.3.0-27ubuntu1~18.04))编译后的源分配,而不是转置的原始数组。是我做错了什么还是编译器错误?
来源分配
allocate(a(3, 2), source=transpose(b))
是有效的。为 a
指定的形状与源表达式 transpose(b)
的形状相同。结果,a
取给定表达式的值。
编译器给出不同的结果是不正确的。这里不怪输出套路。
gfortran 8 似乎给出了预期的输出。
有趣的是,对于 gfortran 7,如果 b
本身不可分配,则会出现预期结果。
我正在尝试了解我在代码中遇到的错误。当尝试使用数组的转置分配数组时,我在代码中使用了带有 source=transpose(original_array) 的分配语句。但是,使用此方法我没有得到预期的结果。似乎索引关闭了一个并且跳过了源数组的第一行。
示例:
program testalloc
real*8, allocatable :: a(:, :)
real*8, allocatable :: b(:, :)
allocate(b(2, 3))
b(1, :) = [1, 2, 3]
b(2, :) = [4, 5, 6]
call printmat(b)
a = transpose(b)
call printmat(a) ! Good
deallocate(a)
allocate(a(3, 2), source=transpose(b))
call printmat(a) ! Bad
deallocate(a)
allocate(a(3, 2))
a = transpose(b)
call printmat(a) ! Good
contains
subroutine printmat(mat)
real*8, intent(in) :: mat(:, :)
integer :: i
write(*,*) 'print'
do i = 1, size(mat, 1)
write(*,*) mat(i, :)
end do
end subroutine
end program
这给出了
print
5.0000000000000000 3.0000000000000000
6.0000000000000000 0.0000000000000000
3.2114266979681025E-322 5.0000000000000000
使用 gfortran(gcc 版本 7.3.0(Ubuntu 7.3.0-27ubuntu1~18.04))编译后的源分配,而不是转置的原始数组。是我做错了什么还是编译器错误?
来源分配
allocate(a(3, 2), source=transpose(b))
是有效的。为 a
指定的形状与源表达式 transpose(b)
的形状相同。结果,a
取给定表达式的值。
编译器给出不同的结果是不正确的。这里不怪输出套路。
gfortran 8 似乎给出了预期的输出。
有趣的是,对于 gfortran 7,如果 b
本身不可分配,则会出现预期结果。