rks171
rks171

Reputation: 1020

Was this feature made available in a recent Fortran Standard?

I was unpleasantly surprised to find that a code I work with would not run when built with gcc v. 4.4.6 because of array size mismatches. It worked fine when built with gcc v. 4.7.3. I created a minimal working example to show the root of the problem:

program main

   implicit none

   integer, allocatable, dimension(:,:) :: array_a
   integer, allocatable, dimension(:,:) :: array_b

   allocate(array_a(5,2))
   allocate(array_b(2,1))

   array_a = 1 

   array_b = array_a

   print *, array_a
   print *, array_b

end program main

When built with gcc v. 4.4.6, it crashes during runtime with error:

At line 13 of file main.f90 Fortran runtime error: Array bound mismatch, size mismatch for dimension 1 of array 'array_b' (1/4)

When build with gcc v. 4.7.3, it produces the following output:

1 1 1 1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1

Note, it automatically resized 'array_b' to match the size of 'array_a'. Is this a 'feature' that is offered by a newer Fortran standard that I'm seeing?

Upvotes: 2

Views: 342

Answers (2)

Kyle Kanos
Kyle Kanos

Reputation: 3264

As Vladimir says, it's a feature of Fortran 2003. If you look at Section 7.4.1.3 of the 2003 working document you'll see,

If variable is an allocated allocatable variable, it is deallocated if expr is an array of different shape or any of the corresponding length type parameter values of variable and expr differ. If variable is or becomes an unallocated allocatable variable, then it is allocated with each deferred type parameter equal to the corresponding type parameters of expr, with the shape of expr, and with each lower bound equal to the corresponding element of LBOUND(expr).

Note 7.36 shows that if you want array_b to keep its shape, you need to declare the line as

array_b(1:2,1) = array_a(3:4,2)

of whatever elements of array_a you want.

Upvotes: 1

You are using a Fortran 2003 feature - automatic array reallocation on assignment. It was not yet implemented in gcc-4.4.

This feature means that the array b, which was allocated to a nonconforming shape before is automatically reallocated to the shape of the right hand side of the assignment. You have to use recent compiler versions (not only GCC), for Fortran 2003 features.

Upvotes: 6

Related Questions