# Dynamic 3D Arrays

This topic is 4169 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm trying to create a 3D array dynamically but I'm having some trouble with that. I can't figure out what I'm doing wrong here:  int*** ImageData = new int[IMAGE_SIZE]; for(int i = 0; i < IMAGE_SIZE; i++) { ImageData = new int[IMAGE_SIZE]; for(int j = 0; j < IMAGE_SIZE; j++) { ImageData[j] = new int[3]; } }  Can someone help?

##### Share on other sites
Quote:
 Original post by AltecZZCan someone help?

Should be something more like
int *** ImageData = new int ** [IMAGE_SIZE];for( int i = 0; i < IMAGE_SIZE; i++ ){	ImageData = new int * [IMAGE_SIZE];	for( int j = 0; j < IMAGE_SIZE; j++ )		ImageData[j] = new int[3];}

At the beginning, you have a pointer to an array of double pointer to integers, but then you're just making an array of straight integers. You should be making an array of double pointers to integers. Similar for the next one.

##### Share on other sites
What you are doing there is creating a pointer to a pointer to a pointer, and then assigning integers to it, causing an error.
The way to create a dynamic three dimensional array is to call new int** and new int* to create arrays of pointers.

Thus:
[SOURCE]int main(){    int *** array;    array = new int**[IMAGE_SIZE]; //Creates an array of pointers to pointers.    for (int i = 0; i < IMAGE_SIZE; ++i)    {        array = new int*[IMAGE_SIZE]; //Creates an array of pointers        for (int j = 0 ; j < IMAGE_SIZE; ++j)        {            array[j] = new int[3]; //Creates the array.        }    }    //I'm not sure that this is the correct way to destroy these arrays.    //So if someone could correct this part,that would be amazing.    for (int i = 0; i < IMAGE_SIZE; ++i)    {        for (int j = 0; j < IMAGE_SIZE; ++j)        {            delete [] array[j];        }        delete [] array;    }    delete [] array;}

##### Share on other sites
Ah, that makes more sense!

What if I wanted them to be unsigned?

I get this error on the first line:

unsigned int *** imageData = unsigned int ** [IMAGE_SIZE];

VS2005 complains about type 'unsigned int' unexpected

##### Share on other sites
Quote:
 Original post by AltecZZI get this error on the first line:unsigned int *** imageData = unsigned int ** [IMAGE_SIZE];VS2005 complains about type 'unsigned int' unexpected

Try:

unsigned int *** imageData = new unsigned int ** [IMAGE_SIZE];

##### Share on other sites
If you're happy using boost in your project you could use boost::multi_array. All the memory management and exception safety issues have been thought through for you. You're also not restricted to 3D.

http://www.boost.org/libs/multi_array/doc/index.html

Edd

1. 1
2. 2
3. 3
Rutin
22
4. 4
5. 5

• 13
• 19
• 14
• 9
• 9
• ### Forum Statistics

• Total Topics
632934
• Total Posts
3009301
• ### Who's Online (See full list)

There are no registered users currently online

×