Creating structs

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Feb 2 04:27:29 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);
> 	}
> }

It *is* a new struct each time:
---
urxae at urxae:~/tmp$ cat test.d
import std.stdio;

struct Test
{ int k = 100; }

void main()
{
         for (int i=0;i < 2; i++)
         {
                 Test t;
                 writefln(t.k);
                 t.k = i;
                 writefln("Pointer: ", cast(int)&t);
         }
}
urxae at urxae:~/tmp$ dmd -run test.d
100
Pointer: -1077296716
100
Pointer: -1077296716
---

But after each iteration of the loop, the struct used is destroyed, and 
the most convenient place to put the next one happens to be the same 
place as the most convenient place to put the last one...


More information about the Digitalmars-d-learn mailing list