Hi I have trouble with implementing a dynamic two dimensional pointer array on allocating memory for it.

I tried it this way but not sure if it's correct. The array should contain pointers to heap allocated Integer objects

``````const int size = 10;
Integer *** twoD;

twoD = new Integer**();

for(int i = 0 ; i < size ; i++)
*twoD[i] = new Integer();
for(int j = 0 ; j < size ; j++)
twoD[i][j] = new Integer();
``````

Any help will be appreciated!

Edited by Phillamon

3
Contributors
5
Replies
7
Views
4 Years
Discussion Span
Last Post by Ancient Dragon

Are you trying to create a 2d array of integers where each dimension is the same size? Here's how to do it. (It's spelled int, not Integer)

Think of a 2d array much like a chessboard which has rows and columns. The rows are the first dimension and the columns are the second dimension. Before you can allocate the columns you have to allocate the rows.

``````const int size = 4;

int** twod = new int[size]; // rows
for(int i = 0; i < size; i++)
twod[i] = new int[size]; // columns
``````

Now, then you destroy that you do it in reverse order, that is delete[] the columns first and then the rows.

Edited by Ancient Dragon

Thanks Ancient Dragonfor your explenation!

The thing is the class name is Integer. How would one change the implementation so that it creates an object(Integer) in each block in a dynamic 2d array? So it's a pointer pointing to a 2d array. That's why I used 2 for-loops in stead of just one. And yes each dimention is the same size.

Is my way of doing correct as indicated in the first post?

I apologise if my first post was a bit vague!

Edited by Phillamon

i think you want an array of pointers to Integer?
is like a cube 3D ))
when you call a value from cube use twoD[x][y][z];
if you wanted just a 2D array remove one asterisk from everywhere
and the last for with his body

``````const int size = 10;
Integer *** twoD;

twoD = new Integer**[size]; // rows

for(int i = 0 ; i < size ; i++) {
twoD[i] = new Integer*[size]; // columns
for(int j = 0 ; j < size ; j++)
twoD[i][j] = new Integer[size]; // depth
}
``````

Edited by thendrluca

Thanks for the help!

Cleared up a few things. It's exactly like you said a 3d cube!

shouldn't it be named threeD instead of twoD??

This question has already been answered. 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.