Hi everyone.
I have a question about derived types and pointers that maybe someone can help
me with. A program that demonstrates the point of confusion appears below.
I have a target array, target_array, and two variables, p_vect1 and p_vect2, of
type pointer_vector, where pointer_vector is a derived type that contains a
vector pointer component.
First I initialise the target array to zero. I point the pointer component of
p_vect1 to an array section of target_array. I then allocate memory for the
pointer component of p_vect2, such that it is the same size as the array
section, and set it to one.
If I set the pointer component of p_vect1 equal to that of p_vect2 (statement
A), then what I would expect to happen happpens. Those elements of the target
which p_vect1 points to are assigned the value one.
However, if I set the derived type p_vect1 equal to the derived type p_vect2
(statememt B), then the pointer component of p_vect1 is set to that of p_vect2,
but those elements of the target to which the pointer component of p_vect1 point
remain zero.
Could someone explain why there is a difference in the effect on the target of
statements A and B please? I expected that equating the derived types in
statement B would involve equating the components of the derived types, and
hence be equivalent to statement A, but it must be more subtle than that.
Also, is it possible to write an INTERFACE ASSIGNMENT(=) operator for the
pointer_vector type that equates the components as statement A does, so that
statement B has the same effect as A on the target?
Cheers,
Paul
PROGRAM test_pointer_vector_prog
IMPLICIT NONE
! Define pointer_vector type
TYPE pointer_vector
INTEGER, POINTER, DIMENSION(:) :: vect
END TYPE pointer_vector
INTEGER, DIMENSION(5), TARGET :: target_array
TYPE(pointer_vector) :: p_vect1
TYPE(pointer_vector) :: p_vect2
! Initialise the target
target_array=0
! p_vect1%vect points to a section of target array
p_vect1%vect => target_array(2:4)
! Allocate p_vect2%vect so that it is the same size as p_vect1%vect
ALLOCATE(p_vect2%vect(SIZE(p_vect1%vect)))
! Set p_vect2%vect
p_vect2%vect=1
! Then, do either statement A:
p_vect1%vect=p_vect2%vect
! ...or statement B:
!p_vect1=p_vect2
! Check what has happened to p_vect1%vect
PRINT '(A,5I2)',' p_vect%vect: ',p_vect1%vect
! Check what has happened to the target array
PRINT '(A,5I2)','target_array: ',target_array
END PROGRAM test_pointer_vector_prog
With statement A, the output is:
p_vect%vect: 1 1 1
target_array: 0 1 1 1 0
With statement B, the output is:
p_vect%vect: 1 1 1
target_array: 0 0 0 0 0
|