allow on stack with betterC
Dennis
dkorpel at gmail.com
Tue Oct 23 11:17:03 UTC 2018
On Tuesday, 23 October 2018 at 10:18:56 UTC, test wrote:
> I can not user static array because the length is a runtime
> vars.
Then you can either:
- use malloc anyway (recommended when the array can be quite
large)
- allocate a static array with an upper bound, and only use a
slice of it
- use alloca to allocate on the stack. Watch out for stack
overflows though.
```
import core.stdc.stdlib: alloca;
import core.stdc.stdio: printf;
extern(C) void main()
{
int n = 5;
ubyte[] tmp = (cast(ubyte*) alloca(ubyte.sizeof * n))[0..n];
tmp[4] = 22;
printf("%d", tmp[4]);
}
```
When compiling with dmd and -betterC I got a linker error
"undefined reference to '__alloca'", but with LDC it worked fine.
More information about the Digitalmars-d-learn
mailing list