On 12/5/15 8:09 AM, John Colvin wrote:
On Saturday, 5 December 2015 at 09:49:06 UTC, ref2401 wrote:
I want to create a static array large enough to store 1MB of float
values.
What am I doing wrong?
Here is a sample code with notes:

void main(string[] args) {
    enum size_t COUNT = 1024 * 512 / float.sizeof; // works OK :)
    //enum size_t COUNT = 1024 * 512 * 2 / float.sizeof; // constantly
crashes :(
    float[COUNT] arr;
    writeln(arr.length);
}

DMD: 2069.2
OS: Win 8.1 Pro

The default stack size is probably 1MB, which means your 1MB array plus
a few local variables is too much. Arrays that large should be allocated
on the heap in most circumstances.

Watch out for this:
static assert(is(typeof(new float[3]) == float[]));
because `new T[n]` is a special case in the grammar. If you really must
have a static array on the heap (as opposed to a dynamic array / slice
T[]), you can use something like this, but i wouldn't recommend it:

T[N]* heapStaticArray(T, size_t N)()
{
     return cast(T[N]*)((new T[N]).ptr);
}

void main()
{
     int[4]* a = heapStaticArray!(int, 4)();
     (*a)[] = 3;
}

T[N]* heapStaticArray(T, size_t N)()
{
   auto arr = new T[N][1];
   return &arr[0];
}

-Steve

Reply via email to