DLang BetterC dynamic arrays

Steven Schveighoffer schveiguy at gmail.com
Mon Dec 24 22:24:17 UTC 2018


On 12/24/18 5:07 PM, dtoadq wrote:
> Ah, of course I find the solution immediately after I post. At least it 
> seems to work fine;
> 
> ```
> struct Array(T) {
>    T[] foo;
> 
>    this ( size_t size ) {
>      T* data = cast(T*)malloc(size);
>      foo = data[0..size];
>    }
> }
> ```

Careful there, data[0 .. size] is for size elements of T.sizeof, not 
bytes (which is what you passed into malloc).

Better:

T* data = cast(T*)malloc(size * T.sizeof);

-Steve


More information about the Digitalmars-d-learn mailing list