C++ – Allocate Memory for 2D Array Using new[]

arraysc++memory-managementmultidimensional-array

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 <iostream>
using namespace std;    
unsigned* numbers;
int main()
{
int a;
cin >> a;
numbers = new unsigned[a];
}

How can I do it with a 2d array(sized a*b read from the user)?

Best Answer

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 :)