2D arrays, slices and manual memory allocation

Nonobvious reply at thisemail.com
Fri Feb 25 06:03:34 UTC 2022


 From [Go Your Own Way (Part Two: The 
Heap)](https://dlang.org/blog/2017/09/25/go-your-own-way-part-two-the-heap/):

`import core.stdc.stdlib;`

     `// Allocate a block of untyped bytes that can be managed`
     `// as a slice.`
     `void[] allocate(size_t size)`
     `{`
         `// malloc(0) is implementation defined (might return 
null `
         `// or an address), but is almost certainly not what we 
want.`
         `assert(size != 0);`

         `void* ptr = malloc(size);`
         `if(!ptr) assert(0, "Out of memory!");`

         `// Return a slice of the pointer so that the address is 
coupled`
         `// with the size of the memory block.`
         `return ptr[0 .. size];`
     }

`T[] allocArray(T)(size_t count) `
`{ `
`    // Make sure to account for the size of the`
`    // array element type!`
`    return cast(T[])allocate(T.sizeof * count); `
`}`

What is the equivalent for higher dimensional arrays?


More information about the Digitalmars-d-learn mailing list