is this the expected output
Dmitry Olshansky
dmitry.olsh at gmail.com
Wed Dec 22 15:39:17 PST 2010
On 23.12.2010 2:16, g g wrote:
> Is this code :
>
> import std.stdio;
> import std.conv;
> struct pt1{
> p val;
> pt1* next;
> }
> struct p{
> int val;
> string toString(){
> return(to!string(val));
> }
> }
Here, notice that thefun is taking pt1 by value - a copy.
> void thefun(pt1 x){
> writeln(&x);
> }
Then you take address of local copy, which is unacceptable. What you
probably wanted is this:
void thefun(ref pt1 x){//reference to the original , but then it must be lvalue
writeln(&x);
}
> void main(){
> auto p0 = p(1);
> auto p1 = p(2);
> auto p2 = p(3);
> auto p3 = p(4);
> p[] arr = [p0,p1,p2,p3];
> writeln(arr);
> foreach(r;arr){
> thefun(pt1(r));
> }
> }
But here you pass a rvalue to function that takes address. In fact, it
prints the address of temporary place in stack used to hold result of
pt1(r).
> supposed to output this:
>
> 1 2 3 4
> BFE61E28
> BFE61E28
> BFE61E28
> BFE61E28 //Note all the addresses are the same
>
> It is expected that using a struct literal(or default constructor) on a bucle reuses the same address?
Yes, inside loop it's likely to use the same address, but actually you
didn't took it but an address of a copy of it ;) Which means you need
to store these temporaries like pt1(r) somewhere, usually on heap (just
as you do with dynamic array of p).
> I got hit by this trying to do a tree structure builder, for hours searching aand finally found this (feature | bug). If so, how I could get a new struct to void changing (in a unnoticeable way) the same struct i just set.
>
> thanks.
> g g
--
Dmitry Olshansky
More information about the Digitalmars-d-learn
mailing list