Ken-Soft

Software and the World

C++ Dynamic Memory Allocation (2D and 3D)

Posted under C/C++, Programming by Kenny on Thursday 8 January 2009 at 4:04 am
Bookmark and Share

This snipped of code is for allocating memory when using a multidimensional array. The following examples are for 2D ([][]) and 3D ([][][]) structures.

First:
to allocate memory for a two dimensional structure: (i.e. int[][] array)

1
2
3
4
5
6
7
8
9
int** array;    // 2D array definition;
// begin memory allocation
array = new int*[dimX];
for(int x = 0; x < dimX; ++x) {
     array[x] = new int[dimY];
     for(int y = 0; y < dimY; ++y) { // initialize the values, this is optional, but recommended
          array[x][y] = 0;
     }
}

Next, to allocate memory for a three dimensional structure: (i.e. int[][][] array)

1
2
3
4
5
6
7
8
9
10
11
12
int*** array;    // 3D array definition;
// begin memory allocation
array = new int**[dimX];
for(int x = 0; x < dimX; ++x) {
    array[x] = new int*[dimY];
    for(int y = 0; y < dimY; ++y) {
        array[x][y] = new int[dimZ];
        for(int z = 0; z < dimZ; ++z) { // initialize the values, again, not necessary, but recommended
            array[x][y][z] = 0;
        }
    }
}

No Comments »

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Copyright © 2009 www.Ken-Soft.com