Simple array init question
Dan
murpsoft at hotmail.com
Mon Apr 9 17:38:03 PDT 2007
Frits van Bommel Wrote:
> Dan wrote:
> > Graham Wrote:
> >> (And to be pedantic, int[5][5] is a 2D rectangular array, which in
> >> memory is exactly the same as int[25] - a 1D array, of course - so six
> >> of one and half a dozen of the other perhaps, but int[5][5] does have >
> >> 1 dimension :-))
> >
> > Actually, you're wrong sir. An int[5][5] produces an array containing 5 structs, each of:
> >
> > struct Array {
> > size_t(or was it int? uint?) length;
> > void* ptr;
> > }
> >
> > Each of those arrays then points to another array of 5 elements.
>
> No, he was right. That struct is only used for dynamic arrays, not with
> static arrays. Static arrays are just a linear row of members stored
> in-place (but passed by reference).
> You don't need to take my word for it, look at what the compilers do:
> =====
> $ cat test.d
> import std.stdio;
>
> int[5][5] matrix;
>
> void main() {
> // Initialize
> foreach (r, inout row; matrix) {
> foreach (c, inout elt; row) {
> elt = r * 5 + c;
> }
> }
>
> // Access as a linear array:
> uint* p = cast(uint*) matrix.ptr;
> // (Note: ".ptr" is not actually stored but inserted as
> // a constant)
> for (size_t i = 0; i < 25; i++) {
> writef(p[i],' ');
> }
> writefln();
> }
> $ dmd -run test.d
> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
> $ gdc -o test test.d && ./test
> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
> =====
Fascinating. I thought static arrays were implemented in the same way (in terms of structure) as dynamic arrays. I'm curious then if I declare a:
struct z { int[] y; }
static z[] x = [ { y:[1,2,3] } ];
Does this implement a static array, or a dynamic array? I *hope* a dynamic one, as otherwise I will have to rewrite my entire Global_init routine for Walnut 2.x. : o
> > What I believe you want is a rectangular array:
> >
> > int[5,5], which will produce a single Array struct that you can access via taking a multiple of the first index added to the second index (or is it vice versa?)
>
> Sorry, "int[5,5]" only compiles because of the obscure comma operator.
According to the D spec, that should compile as a rectangular array. I haven't tried it. I have read the spec.
See:
http://digitalmars.com/d/arrays.html
and visit "Rectangular Arrays".
PS: Walter, any chance we can get <a name=""> so we can link directly to specific parts of the spec?
More information about the Digitalmars-d
mailing list