Allocate memory for 2D array with C++ new[]

后端 未结 8 1392
情深已故
情深已故 2020-12-22 01:04

When I read some values from the user and I need to create an array of the specific size I do it somehow like this:

#include 
using namespace         


        
8条回答
  •  悲&欢浪女
    2020-12-22 01:50

    Anything that would look like a 2D-Array in code will not be a physical 2D array in memory, but either one plain block of memory or scattered, depending on how you allocate it.

    • You can torture yourself by doing dynamic allocation of N arrays in another dynamic array of N pointers, like nrussel's answer suggests.
    • You can make a vector of vectors instead, like billz and Arun C.B suggest - that would relieve you from managing the allocated memory yourself but still leave you with N+1 scattered allocations which is not very performant.
    • Brennan Vincent's answer suggests allocation of one dynamic array, containing a*b elements, which gives you one continuous block in memory. Combine that with the builtin dynamic memory management of std::vector he mentioned and be happy:

      std::vector matrix(a*b);

    If you want the matrix to be convenient to access, wrap the whole thing into a class providing you access to the elements with 2D-coordinates. But please step away from managing the memory yourself. It just hurts you and anyone who has to maintain that code (and search for mem leaks).

提交回复
热议问题