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)?
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.
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::vectorhe mentioned and be happy:std::vector<unsigned> 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).