www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Creating structs

reply Simen Haugen <simen norstat.no> writes:
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);
	}
}
Feb 02 2007
next sibling parent reply Frits van Bommel <fvbommel REMwOVExCAPSs.nl> writes:
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 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 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...
Feb 02 2007
parent reply Simen Haugen <simen norstat.no> writes:
Frits van Bommel Wrote:
 It *is* a new struct each time:

 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...

I see. I stored the pointer in another array, so I thought it wouldn't go out of scope. I guess this only works for object allocated on the heap...?
Feb 02 2007
parent BCS <BCS pathlink.com> writes:
Simen Haugen wrote:
 
 I see. I stored the pointer in another array, so I thought it wouldn't
 go out of scope. I guess this only works for object allocated on the
 heap...?

exactly, struct are stored like ints, on the stack and accessing them is invalid after the end of that scope.
Feb 02 2007
prev sibling parent torhu <fake address.dude> writes:
Simen Haugen wrote:
 I thought that if I create a struct in a loop, a new struct would 


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);
Feb 02 2007