On Friday, 26 March 2021 at 14:27:58 UTC, Jack wrote:
On Friday, 26 March 2021 at 06:45:39 UTC, Daniel Kozak wrote:
On Fri, Mar 26, 2021 at 7:36 AM Daniel Kozak <kozz...@gmail.com> wrote:

On Fri, Mar 26, 2021 at 7:31 AM Daniel Kozak <kozz...@gmail.com> wrote:

On Fri, Mar 26, 2021 at 6:50 AM Jack via Digitalmars-d-learn < digitalmars-d-learn@puremagic.com> wrote:

What's the equivalent of C's VLA in D? scoped from std.typecons doesn't seem to work with arrays. Should I use alloca() for my array or is there something else?


https://dlang.org/library/std/array/static_array.html

Sorry I was misread this


You can use allocator:

import std.experimental.allocator.showcase;
import std.experimental.allocator;
import std.stdio;

StackFront!4096 stackAlloc;

void main() {
    int[] a = stackAlloc.makeArray!int(2);
    writeln(a);
}

I thought this was going to use alloca() but it seems to be using malloc() internally?

Basically, StackFront is an allocator that allows any size allocation, but prefers to put things in its memory block on the stack. If there's no space left on the stack, it puts things on the heap. Not quite what you're asking for, in other words.

StackFront is basically this:

struct StackFront(size_t size) {
    ubyte[size] memory;
    size_t used;
    T allocate(T)() {
if (used + T.sizeof > size) return *cast(T*)malloc(T.sizeof);

         auto result = *cast(T*)&memory[used];
         used += T.sizeof;
         return result;
    }
}

With more bells and whistles, but it's a fixed-size block of memory on the stack that falls back to heap allocation when there's no more room in the block.

alloca is probably your best bet if you need dynamic-size stack allocation. That said, it's a "you're on your own" kind of solution. Use it if you know it's the best solution for your problem.

--
  Simen

Reply via email to