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 :)
Well, the direct equivalent is like this:
// allocate memories related to the number of rows
double** matrix = new double*[row];
// allocate memories related to the number of columns of each row
for(i = 0; i < row; i++)
{
matrix[i] = new double[column];
}
// usage here
// de-allocate memories related to the number of columns of each row
// (YOU FORGOT THIS IN YOUR ORIGINAL CODE!!!)
for(i = 0; i < row; i++)
{
delete matrix[i];
}
delete[] matrix;
Really, though, you don't want this. It's a complete mess and has like no memory locality.
Not to mention all that manual memory management is totally error-prone, as evidenced by the fact that you have a leak of row
double
s in your original code.
What's wrong with this:
struct Matrix
{
Matrix(const unsigned int row, const unsigned int column)
: row(row)
, column(column)
, data(row*column, 0)
{}
double& at(const unsigned int y, const unsigned int x)
{
return data[y + x*row];
}
private:
const unsigned int row, column;
std::vector<double> data;
};
It uses vector
to avoid any of that nasty memory management, and wraps 2D index access around what's actually a single data buffer so that you don't have n pointer indirections.
You can adjust the layout to be row-major or column-major depending on your needs.
Best Answer
If your row length is a compile time constant, C++11 allows
See this answer. Compilers like gcc that allow variable-length arrays as an extension to C++ can use
new
as shown here to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable.Another efficient option is to do the 2d indexing manually into a big 1d array, as another answer shows, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap).
Otherwise, you can use an array of pointers to arrays to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this:
The above, for
colCount= 5
androwCount = 4
, would produce the following:Don't forget to
delete
each row separately with a loop, before deleting the array of pointers. Example in another answer.