A couple of questions about arrays and slices

Cecil Ward cecil at cecilward.com
Thu Jun 22 00:10:19 UTC 2023


On Wednesday, 21 June 2023 at 15:48:56 UTC, H. S. Teoh wrote:
> 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

Is .reserve()’s argument scaled by the entry size after it is 
supplied, that is it is quoted in elements or is it in bytes? I’m 
not sure whether the runtime has a knowledge of the element type 
so maybe it doesn’t know anything about scale factors, not sure.


More information about the Digitalmars-d-learn mailing list