arrays && functions && pointers

Hasan Aljudy hasan.aljudy at gmail.com
Sun Jun 18 22:15:23 PDT 2006



Jarrett Billingsley wrote:
> "Jarrett Billingsley" <kb3ctd2 at yahoo.com> wrote in message 
> news:e751ri$2709$1 at digitaldaemon.com...
> 
> 
>>>btw. How do I reset all the data of a rectangular array?
>>>something like:
>>>tiles[][]=0;
> 
> 
> Damn news client.  Ctrl + Enter posts, apparently.
> 
> I assume your array is of a static size (thus making it a rectangular 
> array).  You can do this:
> 
> foreach(/* auto */ a; tiles)
>     a[] = 0;
> 
> (I just put the /* auto */ in there to let me know when I'm using the dirty, 
> nonobvious foreach index type inference)
> 
> Or, and this is a little hackish, but you can take advantage of the layout 
> of rectangular arrays, which is a single block of memory:
> 
> ((cast(TILE*)tiles.ptr)[0 .. TILEW * TILEH])[] = 0;
> 
> Basically, you're converting the rectangular array type into a linear array 
> type, and setting all those elements to 0.  I would imagine this would be 
> somewhat faster, since it's doing one block set, rather than one block for 
> each row. 
> 
> 


This won't work if the array is dynamically allocated.

Dynamic 2D arrays in are not exactly c-style rectangular arrays; they 
are arrays of pointers to arrays of pointers. In C# they call this 
"jagged arrays".

see:
http://www.digitalmars.com/d/arrays.html
scroll down to "Rectangular Arrays"
<quote>
(Dynamic arrays are implemented as pointers to the array data.) Since 
the arrays can have varying sizes (being dynamically sized), this is 
sometimes called "jagged" arrays. Even worse for optimizing the code, 
the array rows can sometimes point to each other! Fortunately, D static 
arrays, while using the same syntax, are implemented as a fixed 
rectangular layout
</quote>

 > I assume your array is of a static size

Is there a way in D to test for this? anything like:
assert( isStaticallyAllocated( tiles ) );
would be nice in this case, but I don't think it's possible.

I would rather use a one-dimensional array and treat it as if it were 
rectangular. Maybe a little template magic can help ease this task.





More information about the Digitalmars-d-learn mailing list