Inserting into zero-length dynamic array
Steven Schveighoffer
schveiguy at gmail.com
Tue Jul 4 19:28:56 UTC 2023
On 7/4/23 3:19 PM, Cecil Ward wrote:
> I have a dynamic array of strings of length zero. When i write to the
> first element the program crashes, not surprisingly, but what should I
> be doing?
>
> dstring[] arr;
>
> arr[0] = "my string"d; // BANG !!
It depends on the semantic requirement.
If the requirement is "ensure that the array length is at least one, and
then write the first element" then it would be:
```d
if(arr.length < 1) arr.length = 1;
arr[0] = "my string"; // btw, literals will auto-convert to the right width
```
If the requirement is to add another element to a known zero-length
array, then it would just be:
```d
arr ~= "my string";
```
-Steve
More information about the Digitalmars-d-learn
mailing list