<p>I need to create a 2D int array of size 800x800.  But doing so creates a stack overflow (ha ha).</p>

<p>I'm new to C++, so should I do something like a vector of vectors?  And just encapsulate the 2d array into a class?</p>

<p>Specifically, this array is my zbuffer in a graphics program.  I need to store a z value for every pixel on the screen (hence the large size of 800x800).</p>

<p>Thanks!</p>

[{'answer_id': 61684, 'author': 'Adam Mitz', 'author_id': 2574, 'author_profile': 'https://Stackoverflow.com/users/2574', 'pm_score': 5, 'selected': True, 'text': '<p>You need about 2.5 megs, so just using the heap should be fine.  You don\'t need a vector unless you need to resize it.  See <a href="https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays" rel="nofollow noreferrer">C++ FAQ Lite</a> for an example of using a "2D" heap array.</p>\n\n<pre><code>int *array = new int[800*800];\n</code></pre>\n\n<p>(Don\'t forget to <code>delete[]</code> it when you\'re done.)</p>\n'}, {'answer_id': 61685, 'author': 'Niall', 'author_id': 6049, 'author_profile': 'https://Stackoverflow.com/users/6049', 'pm_score': 2, 'selected': False, 'text': '<p>You could do a vector of vectors, but that would have some overhead. For a z-buffer the more typical method would be to create an array of size 800*800=640000.</p>\n\n<pre><code>const int width = 800;\nconst int height = 800;\nunsigned int* z_buffer = new unsigned int[width*height];\n</code></pre>\n\n<p>Then access the pixels as follows:</p>\n\n<pre><code>unsigned int z = z_buffer[y*width+x];\n</code></pre>\n'}, {'answer_id': 61689, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 2, 'selected': False, 'text': '<p>I might create a single dimension array of 800*800. It is probably more efficient to use a single allocation like this, rather than allocating 800 separate vectors.</p>\n\n<pre><code>int *ary=new int[800*800];\n</code></pre>\n\n<p>Then, probably encapsulate that in a class that acted like a 2D array.</p>\n\n<pre><code>class _2DArray\n{\n  public:\n  int *operator[](const size_t &amp;idx)\n  {\n    return &amp;ary[idx*800];\n  }\n  const int *operator[](const size_t &amp;idx) const\n  {\n    return &amp;ary[idx*800];\n  }\n};\n</code></pre>\n\n<p>The abstraction shown here has a lot of holes, e.g, what happens if you access out past the end of a "row"? The book "Effective C++" has a pretty good discussion of writing good multi dimensional arrays in C++.</p>\n'}, {'answer_id': 61690, 'author': 'Free Wildebeest', 'author_id': 1849, 'author_profile': 'https://Stackoverflow.com/users/1849', 'pm_score': 1, 'selected': False, 'text': '<p>There\'s the C like way of doing:</p>\n\n<pre><code>const int xwidth = 800;\nconst int ywidth = 800;\nint* array = (int*) new int[xwidth * ywidth];\n// Check array is not NULL here and handle the allocation error if it is\n// Then do stuff with the array, such as zero initialize it\nfor(int x = 0; x &lt; xwidth; ++x)\n{\n    for(int y = 0; y &lt; ywidth; ++y)\n    {\n         array[y * xwidth + x] = 0;\n    }\n}\n// Just use array[y * xwidth + x] when you want to access your class.\n\n// When you\'re done with it, free the memory you allocated with\ndelete[] array;\n</code></pre>\n\n<p>You could encapsulate the <code>y * xwidth + x</code> inside a class with an easy get and set method (possibly with overloading the <code>[]</code> operator if you want to start getting into more advanced C++). I\'d recommend getting to this slowly though if you\'re just starting with C++ and not start creating re-usable fully class templates for n-dimension arrays which will just confuse you when you\'re starting off.</p>\n\n<p>As soon as you get into graphics work you might find that the overhead of having extra class calls might slow down your code. However don\'t worry about this until your application isn\'t fast enough and you can profile it to show where the time is lost, rather than making it more difficult to use at the start with possible unnecessary complexity.</p>\n\n<p>I found that the C++ lite FAQ was great for information such as this. In particular your question is answered by:</p>\n\n<p><a href="http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.16" rel="nofollow noreferrer">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.16</a></p>\n'}, {'answer_id': 61693, 'author': 'ReaperUnreal', 'author_id': 4218, 'author_profile': 'https://Stackoverflow.com/users/4218', 'pm_score': -1, 'selected': False, 'text': "<p>Well, building on what Niall Ryan started, if performance is an issue, you can take this one step further by optimizing the math and encapsulating this into a class.</p>\n\n<p>So we'll start with a bit of math. Recall that 800 can be written in powers of 2 as:</p>\n\n<pre><code>800 = 512 + 256 + 32 = 2^5 + 2^8 + 2^9\n</code></pre>\n\n<p>So we can write our addressing function as:</p>\n\n<pre><code>int index = y &lt;&lt; 9 + y &lt;&lt; 8 + y &lt;&lt; 5 + x;\n</code></pre>\n\n<p>So if we encapsulate everything into a nice class we get:</p>\n\n<pre><code>class ZBuffer\n{\npublic:\n    const int width = 800;\n    const int height = 800;\n\n    ZBuffer()\n    {\n        for(unsigned int i = 0, *pBuff = zbuff; i &lt; width * height; i++, pBuff++)\n            *pBuff = 0;\n    }\n\n    inline unsigned int getZAt(unsigned int x, unsigned int y)\n    {\n        return *(zbuff + y &lt;&lt; 9 + y &lt;&lt; 8 + y &lt;&lt; 5 + x);\n    }\n\n    inline unsigned int setZAt(unsigned int x, unsigned int y, unsigned int z)\n    {\n        *(zbuff + y &lt;&lt; 9 + y &lt;&lt; 8 + y &lt;&lt; 5 + x) = z;\n    }\nprivate:\n    unsigned int zbuff[width * height];\n};\n</code></pre>\n"}, {'answer_id': 61936, 'author': 'Kevin', 'author_id': 6386, 'author_profile': 'https://Stackoverflow.com/users/6386', 'pm_score': 3, 'selected': False, 'text': "<p>Every post so far leaves the memory management for the programmer.  This can and should be avoided.  ReaperUnreal is darn close to what I'd do, except I'd use a vector rather than an array and also make the dimensions template parameters and change the access functions -- and oh just IMNSHO clean things up a bit:</p>\n\n<pre><code>template &lt;class T, size_t W, size_t H&gt;\nclass Array2D\n{\npublic:\n    const int width = W;\n    const int height = H;\n    typedef typename T type;\n\n    Array2D()\n        : buffer(width*height)\n    {\n    }\n\n    inline type&amp; at(unsigned int x, unsigned int y)\n    {\n        return buffer[y*width + x];\n    }\n\n    inline const type&amp; at(unsigned int x, unsigned int y) const\n    {\n        return buffer[y*width + x];\n    }\n\nprivate:\n    std::vector&lt;T&gt; buffer;\n};\n</code></pre>\n\n<p>Now you can allocate this 2-D array on the stack just fine:</p>\n\n<pre><code>void foo()\n{\n    Array2D&lt;int, 800, 800&gt; zbuffer;\n\n    // Do something with zbuffer...\n}\n</code></pre>\n\n<p>I hope this helps!</p>\n\n<p>EDIT: Removed array specification from <code>Array2D::buffer</code>. Thanks to Andreas for catching that!</p>\n"}, {'answer_id': 61946, 'author': 'Motti', 'author_id': 3848, 'author_profile': 'https://Stackoverflow.com/users/3848', 'pm_score': 1, 'selected': False, 'text': '<p>One thing you can do is change the stack size (if you really want the array on the stack) with VC the flag to do this is [/F](<a href="http://msdn.microsoft.com/en-us/library/tdkhxaks(VS.80).aspx)" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/tdkhxaks(VS.80).aspx)</a>. </p>\n\n<p>But the solution you probably want is to put the memory in the heap rather than on the stack, for that you should use a <code>vector</code> of <code>vectors</code>.</p>\n\n<p>The following line declares a <code>vector</code> of 800 elements, each element is a <code>vector</code> of 800 <code>int</code>s and saves you from managing the memory manually.</p>\n\n<pre><code>std::vector&lt;std::vector&lt;int&gt; &gt; arr(800, std::vector&lt;int&gt;(800));\n</code></pre>\n\n<p>Note the space between the two closing angle brackets (<code>&gt; &gt;</code>)  which is required in order disambiguate it from the shift right operator (which will no longer be needed in <a href="http://en.wikipedia.org/wiki/C_0x#Angle_bracket" rel="nofollow noreferrer">C++0x</a>).</p>\n'}, {'answer_id': 61960, 'author': 'Andreas Magnusson', 'author_id': 5811, 'author_profile': 'https://Stackoverflow.com/users/5811', 'pm_score': 2, 'selected': False, 'text': '<p>Kevin\'s example is good, however:</p>\n\n<blockquote>\n<pre><code>std::vector&lt;T&gt; buffer[width * height];\n</code></pre>\n</blockquote>\n\n<p>Should be</p>\n\n<pre><code>std::vector&lt;T&gt; buffer;\n</code></pre>\n\n<p>Expanding it a bit you could of course add operator-overloads instead of the at()-functions:</p>\n\n<pre><code>const T &amp;operator()(int x, int y) const\n{\n  return buffer[y * width + x];\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>T &amp;operator()(int x, int y)\n{\n  return buffer[y * width + x];\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>int main()\n{\n  Array2D&lt;int, 800, 800&gt; a;\n  a(10, 10) = 50;\n  std::cout &lt;&lt; "A(10, 10)=" &lt;&lt; a(10, 10) &lt;&lt; std::endl;\n  return 0;\n}\n</code></pre>\n'}, {'answer_id': 61980, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': 1, 'selected': False, 'text': "<p>Or you could try something like:</p>\n\n<pre><code>boost::shared_array&lt;int&gt; zbuffer(new int[width*height]);\n</code></pre>\n\n<p>You should still be able to do this too:</p>\n\n<pre><code>++zbuffer[0];\n</code></pre>\n\n<p>No more worries about managing the memory, no custom classes to take care of, and it's easy to throw around.</p>\n"}, {'answer_id': 62611, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>You can allocate array on static storage (in file's scope, or add <code>static</code> qualifier in function scope), if you need only one instance.</p>\n\n<pre><code>int array[800][800];\n\nvoid fn()\n{\n    static int array[800][800];\n}\n</code></pre>\n\n<p>This way it will not go to the stack, and you not have to deal with dynamic memory.</p>\n"}]
['https://Stackoverflow.com/questions/61680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/396/']