You are here:

C++/dynamic allocation



How are you?
I know how to declare dynamically an array of objects of class MyClass:

MyClass **array=new MyClass *[1000];

But how could I declare a 2-dimensional array dynamically like that. The following won't work:
MyClass **array=new MyClass *[1000][1000];
What would the correct syntax be?


ANSWER: Dear Andres:

Try this:
MyClass ** a = new MyClass * [ 1000 ] ; // a is a two dimensional array

for ( int i = 0 ; i < 1000 ; ++ i )
 a [ i ] = new MyClass [ 1000 ] ;
 for ( int j = 0 ; j < 1000 ; ++ j )
   a [ i ] [ j ] = new MyClass () ;  // a is a two dimensional array

---------- FOLLOW-UP ----------


I've been testing what you sugguested and I have this question. Why does this declaration work:

MyTree **array1 = new MyTree *[1001];
for(i=0; i<1001; i++){array1[i]=new MyTree[1001];}

But why doesn't it work together with an assignment like this:

MyTree **array1 = new MyTree *[1001];
for(i=0; i<1001; i++){array1[i]=new MyTree[1001];}
array1[1][1]=new MyTree();

In other words, why doesn't this array1 work like a normal 2D table?

Everything does work just fine when I use int like here:

 int **array1 = new int *[1001];
 for(i=0; i<1001; i++){array1[i]=new int[1001];}

At the same time I know that the MyTree class assignment works because this works just fine for me:

typedef MyTree* pointer_type;
pointer_type(*array1)[101]=new pointer_type[1000][101];
array1[1][1]=new MyTree();


Dear Andres:

Okay, this should work then:

MyTree **array1 = new MyTree *[1001];
for(i=0; i<1001; i++){array1[i]=new MyTree * [1001];} // Here, apparently I did not have you allocate big enough elements in the array.
array1[1][1]=new MyTree();  


All Answers

Answers by Expert:

Ask Experts


Titus B. Ledbetter, Jr.


C , MFC, Object Oriented, Artificial Intelligence


I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Master's Degree Computer Science from Johns Hopkins

©2016 All rights reserved.