digitalmars.D.learn - Inserting into zero-length dynamic array
- Cecil Ward (5/5) Jul 04 2023 I have a dynamic array of strings of length zero. When i write to
- Steven Schveighoffer (14/21) Jul 04 2023 It depends on the semantic requirement.
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
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