Discussion Locked

Dynamic memory allocation in C++ using n

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
How can I allocate dynamic memory for a double dimension array using the new operator in C++. I am able to initilize a single dimension array but what about double dimensions. Please help me

5 replies

by ktirf

Unfortunately, there are no simple and robust ways of doing it. The simpliest is to do this:

int a[10][15] = new int[10*15];

It is quite unsafe, and looks badly. More complex, but more safe, is to use STL containers. It is not always applicable, but at least it is quite convenient in programming.

vector > *a = new vector >;

The problem is that you cannot specify the size. But concerning vector<>, it is even not needed.
Some tasks may be accomplished by usingdictionaries (also known as maps), with the pair of indexes as a key and a value of the correspondent cell in the array as a value. I'd write it like this:

map, int> a;

a[make_pair(1,2)] = 10;

But this works only for so-called sparse arrays.
And the most good-looking and effective, but also the most complex, is to use STL's container named valarray. Your definition would look like this:

valarray a(10*15);

Then you are able to access this array as a two-dimensional via so-called slices. If you are interested, mail me, or read manuals.

by dazza_

As noted in previous answer, cannot be done easily.
You can create a class with overloaded operator() passing two int arguments and constructor that specify the size of the 2d array.

eg:
class A
{
int *space, width;
A(int a, int b)
{ space = new int[a * b]; width = a;}
int& operator()(int a, int b)
{ return space[a*width+b];}
};

hope this code helps

This discussion is closed to new replies.