Fortran 90 doesn't keep lower/upper array bounds after copy to another allocatable array

孤者浪人 提交于 2021-01-27 12:21:26

问题


This doesn't work

program main
   implicit none
   integer :: nx = 3
   integer :: ny = 5
   integer :: nz = 8

   real, allocatable, dimension(:,:,:) :: A
   real, allocatable, dimension(:,:) :: B

   allocate(A(nx,0:ny,nz) )
   ! ...do something with array A and at some point cope a slice of A to B:
   B = A(:,:,1)
   ! in this case B is (1:nx, 1: ny+1) 
end program main

The code above automatically allocates B and copies A(:,:,1) to B. However it doesn't keep the lower/upper bound of 0/ny, instead B has its lower bound to 1 and upper bound to ny+1.

The only way I found to keep the lower/upper bound of A 2dn-dim is by explicitly allocate B as:

   allocate(B(nx, 0:ny))
   B = A(:,:,1)
   ! in this case B is (1:nx, 0:ny)

Given that I have many more variables than in this simple example, Is there a way to assign like B=A(:,:,1) and also keep the bounds of A without explicitly allocate B?


回答1:


A(:,:,1) is an expression. It has bounds (1:nx, 1:ny), BOTH ranks start at 1. It is not the original array, it is a new expression.

However, even if it was an array that had some other lower bounds, automatic allocation always allocates indexes starting from 1. Basically, the right hand side is an expression again.

For your case you do have to allocate explicitly.




回答2:


You can use:

allocate(B(lbound(A,1):ubound(A,1), lbound(A,2):ubound(A,2)))


来源:https://stackoverflow.com/questions/60013236/fortran-90-doesnt-keep-lower-upper-array-bounds-after-copy-to-another-allocatab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!