Creating structs
torhu
fake at address.dude
Fri Feb 2 05:39:33 PST 2007
Simen Haugen wrote:
> > I thought that if I create a struct in a loop, a new struct would
be created each time, but if you see below, it's the same object. How
can I create a new struct each iteration?
> >
> > import std.stdio;
> >
> > struct Test
> > {}
> >
> > void main()
> > {
> > for (int i=0;i < 2; i++)
> > {
> > Test t;
> > writefln("Pointer: ", cast(int)&t);
> > }
> > }
> >
A struct is just a regular local variable, ie. allocated on the stack.
Each time 'Test t;' is executed, the same space is initialized. So it's
overwritten, but it doesn't move. Except that empty structs might not
get initialized, even though they have a size of one byte. You can
allocate on the heap with 'new' if you want each instance to be unique.
Try this:
Test* t = new Test;
writefln("Pointer: ", cast(int)t);
More information about the Digitalmars-d-learn
mailing list