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

430 views Asked by At

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 allocating B?

2

There are 2 answers

2
Vladimir F Героям слава On BEST ANSWER

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.

1
mohammad bagher Malekhosseini On

You can use:

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