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.

You can't use vectors?

You can't use vectors?

No, it's an exercise I have to do.

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]

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.