simple array cause exception

前端 未结 4 1143
孤独总比滥情好
孤独总比滥情好 2020-12-12 02:46
#include \"stdafx.h\"

int _tmain(int argc, _TCHAR* argv[])
{
    float x[1000][1000];

    return 0;
}

I get \" First-chance exception at 0x013416

相关标签:
4条回答
  • 2020-12-12 03:17

    float is 4 bytes, so 4 * 1000 * 1000 = 4 megabytes.

    "stack size defaults to 1 MB"

    See here: http://msdn.microsoft.com/en-us/library/tdkhxaks(v=VS.100).aspx

    0 讨论(0)
  • 2020-12-12 03:17

    As others explained, the size of the object is bigger than the (default) size defined for function stack frame. There are two solutions: 1) create an object on the heap, which is likely to be bigger; or 2) increase the function stack frame size, which can be problematic in 32-bit environment, because you can run out of addressable space, but it can easily be done in 64-bits.

    0 讨论(0)
  • 2020-12-12 03:21

    Just declare your array static:

    static float x[1000][1000];
    

    Edited to add:

    Sigh Another silent downvoter. Not that I'm surprised. This is obviously the simplest solution to OP's problem, so it violates the prime tenet of the OOP Komissariat: The simplest solution is always wrong.

    0 讨论(0)
  • 2020-12-12 03:26

    Your array is simply too large to fit on the stack. You don't have enough stack space for 1000 * 1000 elements.

    You'll need to allocate your array on the heap. You can do this using the new keyword, but an easier way is to just use std::vector.

    std::vector<std::vector<float> > floats(1000);
    for (unsigned i = 0; i != floats.size(); ++i) floats[i].resize(1000);
    

    This will give you a two-dimensional vector of floats, with 1000 elements per vector.

    Also see: Segmentation fault on large array sizes

    0 讨论(0)
提交回复
热议问题