Struct copy, how?

nobody somebody at somewhere.com
Fri Jan 2 19:37:15 PST 2009


(D 1.0)

After some problems with my program I found where my problems arose.

In my mini example: A function that is supposed to create a new bear from 2 
exisiting bears ends up altering the original bears.
I suspect it has to do with the line ' Bear newBear = bear1;', in that it 
doesn't copy the contents of the struct.
Is there a way to copy a struct without resorting to iterating over all its 
elements manually?

module main;

import std.stdio;


struct Claw
{
 int n;
}

struct Bear
{
 Claw[] claw;
}

struct StoredBears
{
 Bear[] bear;
}
StoredBears storedBears;


Bear mixBears(Bear bear1, Bear bear2)
{
 Bear newBear = bear1;

 writefln(storedBears.bear[0].claw[0].n);
 writefln(storedBears.bear[1].claw[0].n);
 writefln(bear1.claw[0].n);
 writefln(bear2.claw[0].n);
 writefln(newBear.claw[0].n);
 writefln();

 newBear.claw[0].n = bear2.claw[0].n;

 writefln(storedBears.bear[0].claw[0].n);
 writefln(storedBears.bear[1].claw[0].n);
 writefln(bear1.claw[0].n);
 writefln(bear2.claw[0].n);
 writefln(newBear.claw[0].n);

 return newBear;
}


void main()
{
 //create 2 bears and put them in the storedBears struct created above
 Bear storedBear1;
 storedBear1.claw.length = 1;
 storedBear1.claw[0].n = 1;
 storedBears.bear ~= storedBear1;

 Bear storedBear2;
 storedBear2.claw.length = 1;
 storedBear2.claw[0].n = 2;
 storedBears.bear ~= storedBear2;

 //create a new bear from the 2 bears
 Bear newBear = mixBears(storedBears.bear[0],storedBears.bear[1]);
}




More information about the Digitalmars-d-learn mailing list