A couple of questions about arrays and slices

H. S. Teoh hsteoh at qfbox.info
Wed Jun 21 15:48:56 UTC 2023


On Wed, Jun 21, 2023 at 02:09:26AM +0000, Cecil Ward via Digitalmars-d-learn wrote:
> First is an easy one:
> 
> 1.) I have a large array and a sub-slice which I want to set up to be
> pointing into a sub-range of it. What do I write if I know the start
> and end indices ? Concerned about an off-by-one error, I have
> start_index and past_end_index (exclusive).

array[start_idx .. one_past_end_idx]


> 2.) I have a dynamic array and I wish to preinitialise its alloc cell
> to be a certain large size so that I don’t need to reallocate often
> initially. I tell myself that I can set the .length property. Is that
> true?

You can use `array.reserve(preinitSize);`.


> 2a.) And what happens when the cell is extended, is the remainder
> zero-filled or remaining full of garbage, or is the size of the alloc
> cell something separate from the dynamic array’s knowledge of the
> number of valid elements in it ?

The size of the allocated cell is managed by druntime. On the user code
side, all you know is the slice (start pointer + length).  The allocated
region outside the current array length is not initialized.  Assigning
to array.length initializes the area that the array occupies after the
length has been extended.


T

-- 
Ph.D. = Permanent head Damage


More information about the Digitalmars-d-learn mailing list