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

后端 未结 8 1395
情深已故
情深已故 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:30

    If a and b are the number of rows and number of columns, respectively, you may allocate the array like this:

    new unsigned[a * b];
    

    To access the element at row i and column j, do this:

    numbers[i * b + j]
    

    However, note that in reality you're almost certainly better off using std::vector for whatever you're trying to do, but you may not have learned about that yet :)

提交回复
热议问题