Creating fixed array on stack

Dgame r.schuett.1987 at gmail.com
Fri Jan 11 15:23:08 UTC 2019


On Friday, 11 January 2019 at 14:46:36 UTC, Andrey wrote:
> Hi,
> In C++ you can create a fixed array on stack:
>> int count = getCount();
>> int myarray[count];
>
> In D the "count" is part of type and must be known at CT but in 
> example it is RT.
> How to do such thing in D? Without using of heap.

You could try alloca:

----
import core.stdc.stdlib: alloca;

pragma(inline, true) auto stack(T, alias len)(void* p = 
alloca(T.sizeof * len)) {
     return (cast(T*) p)[0 .. len] = T.init;
}

void main() {
     import std.stdio: writeln;

     int size = 42;
     auto a = stack!(int, size);
     writeln(a);
     a[] = 2;
     writeln(a);
}
----


More information about the Digitalmars-d-learn mailing list