Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28454 Discussions

doubt for using poingers as components of derived data types

cepheid
Beginner
263 Views
programtest

implicitnone

typedata
real::val
type(data),pointer::next
endtypedata
type(data)::a,b

!--BODY--
allocate(a%next)
a%next%val=1.

b=a
b%next%val=2.

write(*,*)a%next%val,b%next%val

endprogramtest



See the above program, what I mean is that "a" and "b" should be indepedant, the out result should be " 1. 2.".

While after compiling and running, the actual output is "2. 2.".

So Why "a" and "b" are linked as the same? How to keep "a" and "b" indepedant after "b=a"?
0 Kudos
3 Replies
mecej4
Honored Contributor III
263 Views
The confusion here supports the view that pointers are troublesome and should be used, with care, only when necessary.

After the assignment b = a, the components a%next and b%next point to the same variable. Therefore, the next statement, b%next%val=2., results in changing a%next%val also (noting that a%next and b%next point to the same variable).

You may find it instructive to run this program under the debugger, watching the changes to the components of a and b.
0 Kudos
cepheid
Beginner
263 Views
If I want to pass the a structure to b( the a%next has been allocated), and I don't want a and b linked together after b=a, So how to avoid the error?
0 Kudos
mecej4
Honored Contributor III
263 Views
You cannot use pointers and ask that pointers not have the properties of pointers! Nor can you ask pointers to have certain properties only some of the time.

My recommendation: do not be seduced by the apparent convenience of pointers.
0 Kudos
Reply