0

How can I allocate a 2D array? (on the heap) It needs to be dynamically allocated because the values of rows and columns aren't known.

4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by ArkM
0

Make pointer to pointer **ptr , and allocate n pointers to it.
Then to each of that n pointers *ptr[i] allocate n int's (or whatever).
After that you can use it as regular 2D array: ptr[i][j]

0

It's not a problem to allocate 2D array or what else in C++. The problem is: how do you want access the allocated storage. You know that it's impossible to declare 2D array variable with run-time defined extents in C and C++.

The most straightforward approach in C style but with templates (w/o argument check):

template <typename T>
T** new2D(size_t m, size_t n)
{
    T** pp = new T*[m];
    T*  p = new T[m*n];
    for (size_t i = 0; i < m; ++i, p += n)
        pp[i] = p;
    return pp;
}
...
double** pa2d = new2D<double>(m,n);
... pa2d[i][j]...
// to deallocate:
    delete pa2d[0];
    delete pa2d;

More elaborated approaches: define your own class encapsulated all mechanics described above, use vector<vector< >> or valarray<valarray< >> templates. Search this forum: it was a very popular theme 1 or 2 month ago.

Search inet: there are lots of Matrix classes which implements 2D dynamic arrays logics.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.