- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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"?
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"?
Link Copied
3 Replies
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
My recommendation: do not be seduced by the apparent convenience of pointers.
Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page