www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Inserting into zero-length dynamic array

reply Cecil Ward <cecil cecilward.com> writes:
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 !!
Jul 04 2023
parent Steven Schveighoffer <schveiguy gmail.com> writes:
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
Jul 04 2023