static array of structs clarification questions

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 12 13:56:09 PST 2016


On 2/12/16 4:08 PM, WhatMeWorry wrote:
> I was thinking about fixed length arrays of structures the other day so
> I played around with the flowing code:
>
>     struct Foo
>      {
>          int    i;
>          string str;
>          void info() { writeln("i = ", i, "str = ", str); }
>      }
>
>      Foo[2] foos;
>
>      auto f1 = Foo(1, "6chars");  // this string is 6 chars long
>      auto f2 = Foo(2, "ThisVeryVeryVeryLongStringHas36Chars");
>
>      foos[0] = f1;
>      foos[1] = f2;
>
>      writeln("f1 = ", foos[0]);
>      writeln("f2 = ", foos[1]);
>
>      writeln("array foos size in bytes is ", foos.arrayByteSize);
>      writeln("array foos has ", foos.length, " elements");
>      writeln("foos array consists of ", foos);
>
> The output was
> f1 = Foo(1, "6chars", null)
> f2 = Foo(2, "ThisVeryVeryVeryLongStringHas36Chars", null)
> array foos size in bytes is 32
> array foos has 2 elements
> foos array consists of [Foo(1, "6chars", null), Foo(2,
> "ThisVeryVeryVeryLongStri
> ngHas36Chars", null)]
>
>
> question #1: The static array must contain the fat pointers to str
> variables. But where is the string data itself actually held: the stack?
> the heap? somewhere else? (does it vary depending on location or scope)

It's stored in the static data segment. Basically, directly in the 
executable.

> question #2: If the above struct was to contain the same struct and the
> second one contains a third, how would the lower structs be allocated?
> Is it "turtles all the way down?

The only way to compose a struct with itself is to use pointers. You 
can't place a Foo inside a Foo, because it would be infinite in size 
(the compiler will complain)

> question #2: Of what use is the nulls in the array elements? When I took
> out the member function: void info(), the nulls went away.

That's odd. I think anonymous probably has the answer (they are context 
pointers), but I'm also surprised they are null, they shouldn't be.

-Steve



More information about the Digitalmars-d-learn mailing list