Shape and Reshape Command

Greeting, I cannot understand RESHAPE and SHAPE command use in the program at

PROGRAM test_reshape
INTEGER, DIMENSION(4) :: x
WRITE(,) SHAPE(x) ! prints “4”
WRITE(,) SHAPE(RESHAPE(x, (/2, 2/))) ! prints “2 2”
END PROGRAM

When I just use WRITE(,) (RESHAPE(x, (/2, 2/))); result is garbage.

Can someone please provide me guidance as how RESHAPE command works in this program and how SHAPE operates on the complete statement in the last line.

Thanks in advance for guidance

try this

PROGRAM test_reshape
   INTEGER, DIMENSION(4) :: x
   WRITE (*,*) SHAPE(x) ! prints “4”
   WRITE (*,*) SHAPE(RESHAPE(x, (/2, 2/))) ! prints “2 2”
END PROGRAM

The RESHAPE() intrinsic returns a two dimensional array in your example. The SHAPE() intrinsic returns the extents of the one dimensional array in the first statement and of the two dimensional array in the second statement. When you print out the 2D array, the result is garbage because the array x(:) was never defined – it was declared, but values were never given to the elements. The SHAPE() intrinsic works anyway because it does not depend on the values of the array elements, just on the array metadata (i.e. the rank and the extents).