Pointer to Array Element error?

Dragos Carp via digitalmars-d-ldc digitalmars-d-ldc at puremagic.com
Mon Jan 18 02:15:40 PST 2016


On Monday, 18 January 2016 at 09:43:13 UTC, collerblade wrote:
....
>
> struct Node {
>    string name;
>    ...
>    Node[] children;
>
>    Node* search(in string nodeName) {
>       if(name==nodeName) {
>          writeln("returned node: ",&this," name: ",name); 
> //0xABCDEF01 nodename
>          return &this;
>       }
>       foreach(child;children) {

The problem is here. In D the structs have value semantics, i.e. 
child is a stack allocated copy of the element in children and 
consequently an address on stack is returned.
foreach (ref child, children) should solve your problem.

>          auto r=child.search(nodeName);
>          if(r)
>             return r;
>       }
>       return null;
>    }
> }
>

PS: this is a typical post for the learn forum


More information about the digitalmars-d-ldc mailing list