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!

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.

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!

Member Avatar for thendrluca

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
}

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??

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.