I understand from this answer (Fortran copy of pointer) that I should try to use allocatable arrays rather than array pointers as components of derived types. I intend to do so but am locked into my current code for the next year and need to be able to use it and understand it until I can make the bigger and better changes next year.
I also think this question is of some general interest because I think fortran behavior here is pretty unintuitive although apparently correct. So there is likely value in better understanding how and why it works (or else I assume the compiler wouldn't let us do this at all, right?).
Sorry for the longish intro. I'll try to do this as one annotated program that has been whittled down as much as possible:
program main
type tRet
real :: agi
real :: wages_tgt(5) ! compiler won't let me declare as
! target but later I point to this
real, pointer :: wages(:)
end type tRet
type(tRet), target :: ret ! I don't quite understand
type(tRet), target :: orig1, orig2 ! why but compiler insists
! these be targets
ret%wages => ret%wages_tgt(1:1)
ret%wages = (/ 11. /)
orig1 = ret
ret%wages = (/ 99. /)
orig2 = ret
That's the top half of the program, here's some results with print output shown as comments to the right:
! This is not want I want and I was surprised, but it is kind
! of explained in the other answer why this happens, so OK...
print *, "orig1%wages ", orig1%wages ! 99.
print *, "orig2%wages ", orig2%wages ! 99.
! But if I copy from orig1 or orig2 into ret then it
! works like I wanted it to work in the first place!
! But I don't completely understand why it works...
ret = orig1
print *, "ret%wages ", ret%wages ! 11.
print *, "orig1%wages ", orig1%wages ! 11.
print *, "orig2%wages ", orig2%wages ! 11.
ret = orig2
print *, "ret = orig2 "
print *, "ret%wages ", ret%wages ! 99.
print *, "orig1%wages ", orig1%wages ! 99.
print *, "orig2%wages ", orig2%wages ! 99.
end program main
I'm happy for any nice explanation of what is going on here. The irony here, I guess, is that I'm not so worried about why this is a bad idea but rather why does my workaround seem to work fine?
Or maybe the easiest way to summarize my question is: What exactly is pointing to what?
Compiler: GNU Fortran (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16)
associateddebugging output put in your code? At the end, afterret=orig2? - Ross